How to find the longest substring without repeating characters in C++

1 Answer

0 votes
#include <iostream>
 
void findLongestSubstringWithoutRepeatingCharacters(std::string str) {
    size_t n = str.size();
    int start = 0, end = 0;
    int start_sub = 0, end_sub = 0;
    int ASCII[256] = { 0 }; 
  
    while (end < n) {
        if (ASCII[str[end]] > 0) {
            while (str[start] != str[end]) {
                ASCII[str[start]] = 0;
                start++;
            }
            start++;
        }
        else {
            ASCII[str[end]] = end + 1;
            if (end - start > end_sub - start_sub) {
                start_sub = start;
                end_sub = end;
            }
        }
        end++;
    }
  
    for (int i = start_sub; i <= end_sub; i++) {
        std::cout << str[i];
    }
}
  
int main() {
    std::string str = "xwwwqfwwxqwyq";
  
    findLongestSubstringWithoutRepeatingCharacters(str);
}
  
  
  
  
/*
run:
  
xqwy
  
*/

 



answered Jul 18, 2023 by avibootz
edited Jul 18, 2023 by avibootz
...