基本思想就是将串分段进行遍历,变更start的位置
代码1
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| class Solution { public: int lengthOfLongestSubstring(string s) { int m[128] = {0}, len = 0, start = 0; for(int i = 0; i < s.size(); ++i) { ++m[s[i]]; while(m[s[i]] == 2) --m[s[start++]]; len = max(len,i - start + 1); } return len; } };
|
代码2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| class Solution { public: int lengthOfLongestSubstring(string s) { vector<int> map(128, -1); int len = 0,start = 0; for(int i = 0; i < s.size(); i++) { if(map[s[i]] >= start) start = map[s[i]] + 1; map[s[i]] = i; len = max(len,i - start + 1); } return len; }
};
|