leetcode 3 Longest Substring Without Repeating Characters
solution:
1 class Solution { 2 public: 3 int lengthOfLongestSubstring(string s) { 4 std::vector<bool> v(256, false); 5 int len = s.length(); 6 int l=0, ans=0; 7 for (int i = 0; i < len; ++i) { 8 int tmp = s[i]-0x0; 9 if (v[tmp] == true) { 10 ans = std::max(ans, i-l); 11 while (l < i) { 12 if (s[l] == s[i]) { 13 ++l; 14 break; 15 } else { 16 v[s[l]-0x0] = false; 17 } 18 ++l; 19 } 20 } else { 21 v[tmp] = true; 22 } 23 } 24 ans = std::max(ans, len-l); 25 return ans; 26 } 27 };
需要注意这里的字符不仅仅是英文字母,字符char不多于256个,数组范围设
为256即可。O(n)的扫描字符串,每遇到相同的,比对max。