Last active
January 27, 2022 03:25
-
-
Save tjklemz/663423f35b5179857ff39f41f637ae5e to your computer and use it in GitHub Desktop.
numSplits solution without arrays
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#define hash(c) 1 << (c - 'a') | |
int numSplits(char * s) { | |
unsigned int n = 0, l = 0, r = 0, i = 0, j = 0, cur = 0; | |
while (s[i]) { | |
r |= hash(s[i++]); | |
} | |
i = 0; | |
while (s[++i]) { | |
cur = hash(s[i-1]); | |
l |= cur; | |
r &= ~cur; | |
j = i; | |
while(s[j]) { | |
if (cur & hash(s[j++])) { | |
r |= cur; | |
break; | |
} | |
} | |
n += __builtin_popcount(l) == __builtin_popcount(r); | |
} | |
return n; | |
} | |
int main(int argc, char ** argv) { | |
if (argc != 2) return -1; | |
printf("%i\n", numSplits(argv[1])); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
size_t hash(char * s, size_t l) { | |
size_t h = 0, b = 0, i = 0; | |
while (s[i] && (i < l || l < 0)) { | |
b |= (1 << (s[i++] - 'a')); | |
} | |
while (b) { | |
h += b & 1; | |
b >>= 1; | |
} | |
return h; | |
} | |
int numSplits(char * s){ | |
if (!*s) return 0; | |
int n = 0; | |
for (size_t i = 1; s[i]; ++i) { | |
n += hash(s, i) == hash(s+i, -1); | |
} | |
return n; | |
} | |
int main(int argc, char ** argv) { | |
if (argc != 2) return -1; | |
printf("%i\n", numSplits(argv[1])); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment