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.
两个指针,采用hash记录出现字母的位置。
class Solution {
public:
int lengthOfLongestSubstring(string s) {
vector<int>hash (300,-1);
int i,j;
i=0;
j=0;
if(s.size()==0)
return 0;
if(s.size()==1)
return 1;
int ret=0;
while(i<=j && j<s.length()){
if(hash[s[j]]!=-1){
for(;i<hash[s[j]];++i){
hash[s[i]] = -1;
}
i = hash[s[j]]+1;
hash[s[j]]=j;
}
else{
hash[s[j]]=j;
}
ret = max(ret,j-i+1);
++j;
}
return ret;
}
};