Longest Substring Without Repeating Characters(Leetcode medium algorithm problem)

这周刷的题目是Longest Substring Without Repeating Characters,顾名思义,就是找字符串中最长的无重复字母的字串。原题链接


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.


截图思路一贯从最直接和最直观的开始,就是逐个轮询字符串中的字母,向后查询,知道检索到有重复字母为止,记录最长的子串长度即刻。
比如:
abcdacd
先从a开始向右检测,到第二个a,开始遇到重复字符,记录长度为4。
再从b开始向右检测,到第二个c,遇到重复字符,记录长度为4。
以此类推。

但是,这样的做法注定是超时的,因为有很多重复检索,以下为两种应该避免的重复。
1.重复点以前的字符没有必要再检索,比如上例:
abcdacd,当从第一个a向右检测到第二个a时,我们下一次检索的原点为b,但检索的起始点不是第3个字符c,而是第6个字符c,因为两个a之间的字符注定是没有重复的,这在第一次检索的时候就已经注定了。
2.abcdcd,当第一次从a向右检索到第2个c发现有重复字符时,第二次检索的原点就不应该是第2个字符b,而是第4个字符d,因为在第一轮的时候已经发现,第一个c以前的任意字符作为原点向右检索,都会在第二个c那里停止,而且长度短于第一次。

好了,有了上诉两个约束之后,直接上代码提交。

int check(string s, int begin, int end) {
    for (int i = begin; i < end; i++) {
        if (s[end] == s[i]) {
            return i;
        }
    }
    return -1;
}

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int max_length = 0;
        int begin = 0;
        int end = 0;
        int hit_pos = 0;
        int cur_length = 0;
        while (end != s.size()) {
            hit_pos = check(s, begin, end);
            if (hit_pos != -1) {
                cur_length = end - begin;
                if (cur_length > max_length) {
                    max_length = cur_length;
                }
                begin = hit_pos + 1;
            }
            end++;
        }
        cur_length = end - begin;
        if (cur_length > max_length) {
            max_length = cur_length;
        }
        return max_length;
    }
};

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值