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.
用一个数组记录每个字符出现的位置,遇到重复的,从上一个出现位置继续O(n)
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int used[256];
memset( used, 0, sizeof(used));
int tmp = 0, maximum = 0;
for( int i = 0; i < s.size(); ++i){
if( used[s[i]] > 0){
i = used[s[i]] - 1;
memset( used, 0, sizeof( used));//这里注意不要大意
maximum = max( maximum, tmp);
tmp = 0;
}
else{
used[s[i]] = i + 1;
++tmp;
}
}
return max( maximum, tmp);//别忘了最后一次
}
};