The reason you get the wrong result is because the basic approach lacks several moving parts. You do not track all the information necessary for its calculation. You not only need to keep track of which characters you saw, but also in what position in the line in which they were seen (I suppose you want to keep this with O (n) complexity).
Thus, when you see a character that you met before, you need to reset the "consecutive non-repeating characters seen so far" to start after the previous appearance of the same character that you are looking at at the current position. In addition, all the characters that have been seen so far, to this point, are no longer visible, because if you think about it for a second, this should make sense to you.
This is the missing part from your implementation. In addition, it does not track the position of the longest line, absolutely correctly.
Below are the results you were looking for.
Let us know what class you got for your homework :-)
#include <iostream> #include <cstdio> #include <string> #include <algorithm> #include <vector> using namespace std; int main() { string s = "aaaaaaaaaaaaasadfrhtytbgrbrsvsrhvsg"; vector<bool> v(256,false); vector<int> seen_at(256); int longest_starting_pos=0, longest_length=0; int current_length=0; for (int i=0; i<s.length(); i++) { if (v[s[i]]) { for (int j=i-current_length; j<seen_at[s[i]]; ++j) v[s[j]]=false; current_length=i-seen_at[s[i]]-1; } v[s[i]]=true; seen_at[s[i]]=i; if (++current_length > longest_length) { longest_length=current_length; longest_starting_pos=i-current_length+1; } } cout<<s.substr(longest_starting_pos, longest_length)+" "<<longest_length<<endl; }
source share