Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc"
, with the length of 3.
Example 2:
Input: "bbbbb"
Output: 1
Explanation: The answer is "b"
, with the length of 1.
Example 3:
Input: "pwwkew" Output: 3 Explanation: The answer is"wke"
, with the length of 3. Note that the answer must be a substring,"pwke"
is a subsequence and not a substring.
思路:滑动窗口也叫做双指针。维护一左一右两个指针,两个指针之间的是无重复的字母。
注意:1,考虑左右指针如何向右移动
2,注意边界,何时退出
3,如何判断两个指针之间字母无重复
代码:
class Solution {
public:
map<char,int> count;
int lengthOfLongestSubstring(string s) {
if(s.length()==0) return 0;
int left,right;
int ans = 1;
left=0;
right=0;
count[s[right]]+=1;
right++;
while(1)
{
if(right>=s.length()) break;
count[s[right]]+=1;
while(count[s[right]]>1)
{
count[s[left]]--;
left++;
}
ans = max(ans,right-left+1);
right++;
}
return ans;
}
};