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的思想,存储字符上一次出现的位置,并在遍历字符串的过程中设立指针start
字符当前位置与start的差 即为最长长度
如果字符上一次的位置大于start,start更新为字符上一次出现位置+1
特别要注意的是最后,当遍历结束后,仍需要一次这样的操作
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int table[256];
for(int t= 0; t< 256; t++){
table[t]= -1;
}
int start= 0, max= 0;
int i;
for(i= 0; i< s.length(); i++){
if((i- start)> max){
max= i- start;
}
if(start< table[s[i]]+ 1) start= table[s[i]]+ 1;
table[s[i]]= i;
}
if((i- start)> max){
max= i- start;
}
return max;
}
};