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
利用map,不同的就加入MAP,如果找到相同的,就把,两次相同的之间的所有char删除
18%
classSolution{
public:
intlengthOfLongestSubstring(strings) {
map<char,int>mapstring;
intiLength=s.length();
intmax_length= 0;
intk= 0;
intl= 0;
map<char,int>::iteratoriterTest;
for(inti= 0;i<iLength;i++)
{
iterTest=mapstring.find(s[i]);
if(mapstring.end()==iterTest)
{
mapstring[s[i]]=i;
}
else
{
for(intj=k;j<i;j++)
{
if((iterTest->second) > j)
{
mapstring.erase(s[j]);
l++;
}
else
{
break;
}
}
mapstring[s[i]]=i;
l++;
k=l;
}
if(max_length<mapstring.size())
{
max_length=mapstring.size();
}
}
returnmax_length;
}
};