思路:begin(最重要的变量)记录longest substring开始的位置;longest当前substring的长度;map存放字符的index。实质上是维护了一个substring区间,使得substring内的所有字符都是独一无二的。
class Solution {
public:
int lengthOfLongestSubstring(string s) {
if (s.length() <= 1){
return s.length();
}
unordered_map<char, int> map;
int ans = 0;
int longest = 0;
int begin = 0;
for (int i = 0; i < s.length(); ++i){
if (map.count(s[i]) == 0 || map[s[i]] < begin){ // 只要map中的字符index不在begin之后,都视为不存在
map[s[i]] = i;
++longest;
}else{
int before = map[s[i]];
map[s[i]] = i;
longest = i - before;
begin = before + 1;
}
if (longest > ans){
ans = longest;
}
}
return ans;
}
};
来源:CSDN
作者:zxc120389574
链接:https://blog.csdn.net/zxc120389574/article/details/104111719