这个题的难点在于一开始没有想到要写left = max(hash[s[right]] + 1, left);而不是left = hash[ s[ right ]] + 1;
代码思路就是很简单的滑动窗口,然后用哈希表记录窗口内有过的字母
class Solution {
public:
int lengthOfLongestSubstring(string s) {
unordered_map<char, int> hash;
int res = 0;
int left = 0;
for(int right = 0; right < s.size(); right++){
if(hash.count(s[right])){
left = max(hash[s[right]] + 1, left);
}
hash[s[right]] = right;
res = max(res, right - left + 1);
}
return res;
}
};