Longest Substring Without Repeating Characters [LeetCode]
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.
Summary: Using map to record a substr, if a duplicate letter is found, then erase letters in map which are from begin of this substr to the previous index of this letter. For example, "abcb", erase "ab" in map when meeting the "b" in string.
1 int lengthOfLongestSubstring(string s) { 2 if(s.size() == 0) 3 return 0; 4 int longest = 0; 5 map<char, int> pattern; 6 for(int i = 0; i < s.size(); i ++) { 7 if(pattern.find(s[i]) == pattern.end()) { 8 pattern[s[i]] = i; 9 } else { 10 int size = pattern.size(); 11 longest = max (longest, size); 12 if(s[i] == s[i - 1]){ 13 pattern.clear(); 14 pattern[s[i]] = i; 15 continue; 16 } 17 int start = i - pattern.size(); 18 int end = pattern[s[i]]; 19 for(int j = start; j <= end; j ++) 20 pattern.erase(s[j]); 21 pattern[s[i]] = i; 22 } 23 } 24 int size = pattern.size(); 25 longest = max(longest, size); 26 return longest; 27 }


浙公网安备 33010602011771号