Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb"
, the answer is "abc"
, which the length is 3.
Given "bbbbb"
, the answer is "b"
, with the length of 1.
Given "pwwkew"
, 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.
思路:滑动窗口和查找表;
题目要求的事 最长的不重复的子串;返回出长度;
这时候需要一个滑动窗口;然后再构建一个查找边查找新的元素是否已经存在;
CODE::
class Solution {
public:
int lengthOfLongestSubstring(string s)
{
int n=s.size();
int left=0;
int right=-1;//滑动窗口 [left,right];
int freq[256]={0};//用来表示记录重复字符串的字典;
int res=0;
while(left<n)
{
if(right+1<n&&freq[s[right+1]]==0)
freq[s[++right]]++;
else
freq[s[left++]]--;//一直循环直到 去除重复 的那个点;
res=max(res,right-left+1);
}
return res;
}
};