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.
Subscribe to see which companies asked this question
分析:
与以前一个求最长自序列和不超过目标值的解法类似。两个边同时考虑收缩,问题是效率比较低。
代码:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int start=0;
int big=0;
map<char,int> m1;
string temp="";
for(int t=0;t<s.size();++t)
{
temp+=s[t];
m1[s[t]]++;
while(m1[s[t]]>1)
{
temp=temp.substr(1,temp.size()-1);
m1[s[start]]--;
int tt=t-start;
if(tt>big)
big=tt;
start+=1;
}
}
return temp.size()>big?temp.size():big;
}
};