#include <iostream>
#include <string>
#include <vector>
/*
* 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)
*/
std::string longestUniqueSubstringASCII(const std::string& s) {
std::vector<bool> seen(256, false); // ASCII presence table
int left = 0, right = 0;
int bestLeft = 0, bestRight = 0;
while (right < static_cast<int>(s.size())) {
unsigned char c = s[right];
if (seen[c]) {
// Shrink window until we remove the duplicate
while (s[left] != c) {
seen[static_cast<unsigned char>(s[left])] = false;
left++;
}
left++; // skip the duplicate itself
} else {
seen[c] = true;
if (right - left > bestRight - bestLeft) {
bestLeft = left;
bestRight = right;
}
}
right++;
}
return s.substr(bestLeft, bestRight - bestLeft + 1);
}
int main() {
std::string str = "xwwwqfwwxqwyq";
std::string result = longestUniqueSubstringASCII(str);
std::cout << "Input: " << str << "\n";
std::cout << "Longest substring without repeating characters: " << result << "\n";
}
/*
run:
Input: xwwwqfwwxqwyq
Longest substring without repeating characters: xqwy
*/