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.
用一个128的hash表来记录字符是否出现过,然后从每位开始往后遍历,思路跟代码很简单。
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int h[128] = {0};
int maxlen = 0;
for (int i = 0; i < s.size(); i++) {
memset(h, 0, sizeof(h));
int len = 0;
for (int j = i; j < s.size(); j++) {
if(h[s[j]] != 1){
h[s[j]] = 1;
len++;
}
else
break;
}
if(len > maxlen)
maxlen = len;
}
return maxlen;
}
};