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 subsequence and not a substring.
two pointers 的题。i代表substring的开始位置,j代表substring的结束位置。注意问题:
1第二个指针从前向后遍历还是从后向前遍历:从前向后,因为可能从第二个字符就开始重复,从后向前不能效率更高
2 第一个指针从哪个位置开始更新:从当前找到的重复字符的位置的下一个开始,形成一个新substring。
3 如何表示当前字符是否重复: 使用一个bool 数组,表示256个字符是否存在在当前substring
4 如何更新bool 数组,只更新头尾。因为两个重复字符之间的字符是不重复的。
5 最后需要比较maxLength和n-i,因为可能j一直到string末尾都没有遇见重复,但是没有更新maxLength
代码如下:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int n = s.size();
if (n == 0) return 0;
if (n == 1) return 1;
int i = 0;
int j = 0;
int maxLength = 0;
bool characters[256] = { false };
while (j < n) {
if (characters[s[j]]) {
maxLength = max(maxLength, j - i);
while (s[i] != s[j]) {
characters[s[i]] = false;//recover the value for next substring
i++;
}
i++;//since substring between i and j are not repeated
j++;
}
else {
characters[s[j]] = true;
j++;
}
}
maxLength = max(maxLength, n - i);
return maxLength;
}
};