// See longunstr.py for details. #include #include #include typedef struct { char *s; size_t n; } str; typedef uint8_t u8; // XXX note: byte case only // This is arguably a bit cleaner than the Python. str longunstr(str s) { size_t pos[256] = {0}, i = 0, j, n = 0, m = 0; for (j = 0; j < s.n; j++) { u8 c = s.s[j]; if (pos[c] > i) i = pos[c]; pos[c] = j + 1; if (j+1 - i > m - n) n = i, m = j+1; } return (str){ .s = s.s + n, .n = m - n }; } // size_t pos[256] = {0}, i = 0, j, n = 0, m = 0; for (j = 0; j < s.n; j++) {u8 c = s.s[j]; if (pos[c] > i) {i = pos[c];} pos[c] = j + 1; if (j+1 - i > m - n) {n = i; m = j+1;}} return (str){ .s = s.s + n, .n = m - n }; void strite(FILE *f, str s) { fwrite(s.s, 1, s.n, f); } int main(int argc, char **argv) { if (argc != 2) { fprintf(stderr, "Usage: %s XabcXYdefY\n" "Print longest substring of XabcXYdefY without repeated bytes.\n", argv[0]); return -1; } printf("longunstr(%s) = ", argv[1]); strite(stdout, longunstr((str){ .s = argv[1], .n = strlen(argv[1]) })); printf("\n"); return 0; }