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.
/*
时间复杂度:O(n)
思路:abacdab
从左到右扫一遍字符串,用mp记录每一个字符最新出来的下标
遇到重复的时候将更新答案
或者遇到重复的 但是之前被删除清零了
例如:adab b是第二次出现了 但是之前有字符a将左边指针更新在了上一个a的下一个字符
所以在那之前的字符都认为没有出现过
*/
class Solution {
public:
int lengthOfLongestSubstring(string s) {
vector<int>mp(256,-1);
int len=s.size();
int res=0;
int j=0;
for(int i=0;i<len;i++)
{
if(mp[s[i]]==-1||mp[s[i]]<j)
res=max(res,i-j+1);
else
j=mp[s[i]]+1;
mp[s[i]]=i;
}
return res;
}
};