刷题[Leetcode]3. 无重复字符的最长子串
3. 无重复字符的最长子串
class Solution {
public:
int lengthOfLongestSubstring(string s) {
if (s.size() == 0) return 0;
unordered_set<int> unset;
int maxLen = 0;
int left = 0;
for(int right = 0; right < s.size(); right++){
while(unset.find(s[right]) != unset.end()){
unset.erase(s[left++]);
}
unset.insert(s[right]);
int curLen = right - left + 1;
maxLen = max(maxLen, curLen);
}
return maxLen;
}
};
右端点移动开始扫描,如果扫描到重复的,就转去处理查重set。
为什么是while而不是if。
原因在于出现重复时,肯定是一个当前右端点与某一个set中的数重复了,但是这个数未必是左端点的,可能只是右端点的前一个
无论是哪种情况,都需要从不重复的数再开始,右端点加入之前一定是不重复的,所以右端点加入之后如果重复,就一直移除set的左端点,并且右移一位。