您的位置:首页 > 其它

LeetCode 3. Longest Substring Without Repeating Characters

2017-08-07 19:11 351 查看
Description:

Given a string, find the length of the longest substring without repeating characters.

For example:

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.

Given “abcabcbb”, the answer is “abc”, which the length is 3.

Given “bbbbb”, the answer is “b”, with the length of 1..

分析:

1. 采用尺取法(我不造是不是这么叫的…)用i, j表示待处理子串的首尾下标(准确来说,j为末尾下标的下一个)这样当前处理子串的长度就可以用j - i来表示了。

2. 刚开始i, j都为0,不断增加i, j直到处理到字符串结尾为止。始终判断s[j]是否在i~j中出现过,若未出现则j++,若出现过则将i增加到i~j中已经出现的位置的下一位。

3. 例如:s = abcb, 当i = 0, j = 2时,s[j] = ‘c’ 未在i~j (0~2)中出现过,则j++, 此时j = 3, s[j] = ‘b’ 在i~j (0~3)中出现过,出现的坐标为1,那么我们就应该将i++到坐标为2的位置继续处理,依此类推。

4. maxlen表示当前满足条件的子串的最长长度,其更新时机为:s[j]的字符在i~j中出现过,或者是j递增到最后一个字符。

5. 那么如何去记录字符是否在i~j中出现过呢?我用的方法是将每个字符的ASCII码作为下标,建立一个只存01的数组,0表示该字符不在i~j内,1则表示存在。

6. 如此下去就可以得出结果了,由于i, j最长处理了长度为n的字符串,因此时间复杂度为o(n)。

注意:maxlen更新的时机

Submission Details:

983 / 983 test cases passed.

Status: Accepted

Runtime: 12 ms

class Solution {
public:
int lengthOfLongestSubstring(string s) {
int i = 0, j = 0, len = s.length();
int maxlen = 0;
int mark[256] = {0}; //标记每一个字符是否在i~j中出现过
while (j < len) {
if (mark[s[j]] != 0) { //若s[j]在i~j中出现过
maxlen = max(maxlen, j - i);
while (s[i] != s[j]) { //找到不重复的字符的下一个字符,重新开始
mark[s[i]] = 0; //标记此后不在i~j的范围内
i++;
}
i++;
} else { //若没有出现过
mark[s[j]] = 1; //标记此后在i~j的范围内
}
j++;
}
maxlen = max(maxlen, j - i);
return maxlen;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode