无重复字符的最长子串 LeetCode热题100
题目
给定一个字符串 s ,请你找出其中不含有重复字符的 最长连续子字符串 的长度。
思路
使用滑动窗口,记录窗口区间的长度大小,取最大值。用map存储滑动窗口内所有字符,字符作为key,每个字符的数量作为value。遍历字符串,当某个字符的数量大于1时窗口不满足要求,移动左侧指针,并且减去map中对应的字符。
代码
class Solution {
public:int lengthOfLongestSubstring(string s) {int left=0,ans=0;map<char,int>mp;for(int i=0;i<s.length();i++){mp[s[i]]++;while(mp[s[i]]>1){mp[s[left++]]--;}int len = i-left+1;if(len>ans){ans=len;}}return ans;}
};