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.
解题思路1,o(n):
新建一个字符串变量sub用来保存当前处理的子字符串,从起始遍历原字符串S中的每个字符;
对于每一个遍历到的字符S[i]:
如果S[i]已存在sub中(例sub[j] = S[i]),则sub切掉sub[j]及其之前的所有字符,并在末尾插入S[i];
如果S[i]不存在sub中,则在sub末尾插入S[i]。
遍历过程中,随时记录sub曾经达到的最大长度maxlength
遍历结束,返回maxlength;
代码:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int string_length = s.size();
if (string_length <= )
return string_length; string substring = string(, s[]);
int current_length = ;
int max_length = ; for (int i = ; i < string_length; ++i) { //current_length + string_length - i > longest_length
int pos = substring.find(s[i]);
if (pos != -) {
substring = substring.substr(pos + ) + s[i];
current_length -= pos;
} else {
substring += s[i];
current_length++;
if (current_length > max_length)
max_length = current_length;
}
} return max_length;
}
};
解题思路2,o(n):
用一个128个元素的int型数组postions,记录字符串中的每个字符,在字符串中上次出现的位置(之前从未出现则为-1);同时用一个int变量ind记录子串的开始位置;
当遍历到字符串某一个元素S[i]时:
查看postion数组中记录的此字符上次出现的位置positions[S[i]],
如果positions[S[i]]大于ind,说明S[i]在当前子串中有重复,则ind = positions[S[i]] + 1;
如果positions[S[i]]小于ind,说明当前子串中,不包含S[i],则ind不变;
随时记录子串的最大长度(i - ind + 1)
循环结束,返回最大长度值。
代码:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int positions[];
memset(positions, -, sizeof(positions)); int ind = ;
int max = ;
for (int i = ; i < s.size(); i++){
if (positions[s[i]] >= ind)
ind = positions[s[i]] + ; if (i - ind + > max)
max = i - ind + ; positions[s[i]] = i;
} return max;
}
};
附录:
C++ string操作