题意是给定一个字符串,返回不含重复字符的最长串长度

例如对于abcabcbb,返回3

ansl记录当前选定串的最左字符位置,用ansr记录当前选定串的最右字符位置

我的做法是用map记录当前选定串中字符的位置,那么当遇到一个新的字符ch时,如果map[ch]的值不为0,说明当前选定串有ch,那就更新当前选定串

每次更新anslansr时,若两者差值大于当前答案res,则更新res

这里所说的ansr就是当前字符的下标i

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
int lengthOfLongestSubstring(string s) {
if(s.size() == 0) return 0;
int ansl, res;
ansl = res = 0;
map<char, int> mp;
s = " " + s;
for(int i=1; i<s.size(); ++i) {
if(mp[s[i]] != 0) {
ansl = max(ansl, mp[s[i]]+1);//保证左侧位置不会“回头”
}
if(ansl == 0) res = max(res, i-ansl);
else res = max(res, i-ansl+1);
mp[s[i]] = i;
}
return res;
}
};