#include <stdio.h>
#include <string.h>
/*
* Finds the longest substring without repeating characters.
* This version keeps a presence table and shrinks the window
* by clearing characters until the duplicate is removed.
*
* Time complexity: O(n)
*/
const char* longest_unique_substring_ascii(const char *str, int *out_len) {
int n = strlen(str);
int seen[256] = {0}; // 0 = not in window, 1 = in window
int left = 0, right = 0;
int best_left = 0, best_right = 0;
while (right < n) {
unsigned char c = str[right];
if (seen[c]) {
// Shrink window until we remove the duplicate
while (str[left] != c) {
seen[(unsigned char)str[left]] = 0;
left++;
}
left++; // skip the duplicate itself
} else {
seen[c] = 1;
if (right - left > best_right - best_left) {
best_left = left;
best_right = right;
}
}
right++;
}
*out_len = best_right - best_left + 1;
return str + best_left;
}
int main() {
const char *str = "xwwwqfwwxqwyq";
int len = 0;
const char *result = longest_unique_substring_ascii(str, &len);
printf("Input: %s\n", str);
printf("Longest substring without repeating characters: ");
fwrite(result, 1, len, stdout);
printf("\n");
return 0;
}
/*
run:
Input: xwwwqfwwxqwyq
Longest substring without repeating characters: xqwy
*/