题意:
Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for “abcabcbb” is “abc”, which the length is 3. For “bbbbb” the longest substring is “b”, with the length of 1.
题解:设置一个窗口,如果窗口为空或者窗口不重复,则移动窗口右边界,若有重复,则移动左边界直到没有重复。
代码如下:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
vector<int> num(128, 0);
int sLen = s.size();
if(sLen == 0) return 0;
int left = -1;
int right = -1;
int maxLen = 0;
while(right < sLen) {
if(right == -1 || num[s[right]] == 1) {
//如果left到right的字符串为不重复的,则移动右窗口探查更长的不重复子串
right++;
if (right == sLen) return maxLen;
num[s[right]]++;
}
else {
//如果有重复,注意此时只会有一个重复,即right位置的字符
left++;
num[s[left]]--;
}
if(num[s[right]] == 1) {
maxLen = max(maxLen, right-left);
}
}
return maxLen;
}
};