Given astring, 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.
public:
int lengthOfLongestSubstring(string s) {
string best;
string temp;
size_t found;
int i=1;
if(s.length()==0) return 0;
if(s.length()==1) return 1;
best.append(1,s.at(0));
temp.append(1,s.at(0));
while(i<s.length())
{
if(temp.find(s.at(i))==string::npos)
{
temp.append(1,s.at(i));
}
else
{
temp.erase(0,(int)temp.find(s.at(i))+1 );//注意需要加1
temp.append(1,s.at(i));
}
if(best.length()<=temp.length())
{
best.clear();
best.resize(temp.length());
best.assign(temp);
}
i++;
}
return best.length();
}
};