LeetCode 3. Longest Substring Without Repeating Characters


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;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值