Problem:
Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
Analysis:
The key of the solution of this problem is in how to find out the new start of a substring without repeated characters. The straightforward way is to set the new start to be the next position of the repeated character. This is because the substrings start from the old start to the repeated character will not be a valid solution (they contain the substring starts and ends by the repeated character which imply the length of substring will not be over the current substring). The tricky part of the solution is the using of hash table. The hash table takes the index of a character appears in the string. Only the indices after the start index of every round of loop are meaningful in the determination of a substring is valid. Then, we do not need to build a new hash table in every round.
Code:
C++:
1 int lengthOfLongestSubstring(string s) { 2 if(s.size() <= 1) 3 return s.size(); 4 5 int start = 0; 6 int max_len = 1; 7 vector<int> hash(256, -1); 8 hash[s[start]] = start; 9 for(int i = 1; i < s.size(); ++i) { 10 if(hash[s[i]] != -1 && hash[s[i]] >= start) 11 start = hash[s[i]] + 1; 12 13 hash[s[i]] = i; 14 15 if(i - start + 1 >= max_len) 16 max_len = i - start + 1; 17 } 18 19 return max_len; 20 }