一、问题描述
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb"
, the answer is "abc"
, which the length is 3.
Given "bbbbb"
, the answer is "b"
, with the length of 1.
Given "pwwkew"
, the answer is "wke"
, with the length of 3. Note that the answer must be a substring, "pwke"
is a subsequenceand not a substring.
基本思路是使用哈希,再使用指针,一个指针为start 指向当前遍历的字串的开始位置,如果遇到重复字符假如为t,就将 start的位置 改为上一个t所在位置+1. 另一个指针i指向当前长度为当前遍历的字串的位置,所以长度为i-start,并且用max时刻记着当前的最大长度。
例如:对于 “abcdbc” 初始 start=0, 当遍历到 第二个 b时,检测到重复。上一个b的位置是1. 因此 start=1+1。 然后还有更新 hash。
三、代码
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int hash[256];
for(int i=0; i<256; i++) hash[i] = -1;
int start = 0, max = 0;
int i;
for(i=0; i<s.size(); i++){
if(hash[s[i]] != -1){
if(max < i - start) {
max = i - start;
}
for (int j = start; j < hash[s[i]]; j++) {
hash[j] = -1;
}
if(hash[s[i]] + 1 > start )
start = hash[s[i]] +1;
}
hash[s[i]] = i;
}
if(max < i-start) {
max = i-start;
}
return max;
}
};