题目:
Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc"
, with the length of 3.
Example 2:
Input: "bbbbb"
Output: 1
Explanation: The answer is "b"
, with the length of 1.
Example 3:
Input: "pwwkew" Output: 3 Explanation: 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.
描述:
给出一个字符串,求最长不重复字符的子串(子串是必须连续的!)的长度。
分析:
用尺缩法....
维护一个数组,来标识某字符是否出现过,随后向后继续遍历,尝试增大不重复子串的长度,并使用length标识的当前所维护串的长度,若某字符已出现过,则从左向右缩短所维护串的长度,直到子串不包含重复的字符,依此运行到字符串遍历结束,在整个过程中,记录length所能达到的最大长度,即为所得。
该算法的时间复杂度O(n),由于只使用了一个容量为256的数组,因此空间复杂度为O(1)。
该题的坑点:
测试数据中会出现除小写字母以外的字符!!!!!!!
所以辅助数组应为拓展ASCII码的最大范围256....
代码:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int length = 0, result = 0, left = 0;
int temp[256] = {0};
for (int i = 0; i < s.size(); ++ i) {
int right = s.at(i);
if (!temp[right]) {//如果某字符未出现过
++ temp[right];
length += 1;
if (length > result) {
result = length;
}
} else {//若某字符第二次出现
++ length;
++ temp[right];//将第二次出现的位置累加
for (int j = i - length + 1; j < i; ++j) {//从左往右缩短,直到不出现重复的字母
-- length;
int left = s.at(j);
-- temp[left];
if (temp[left]) {//说明已经缩到无重复字母的最左侧
break;
}
}
}
}
return result;
}
};