首页 > 其他 > 详细

[滑动窗口] leetcode 3 Longest Substring Without Repeating Characters

时间:2019-08-05 14:38:12      阅读:72      评论:0      收藏:0      [点我收藏+]

problem:https://leetcode.com/problems/longest-substring-without-repeating-characters/

       二刷此题了,发现第二次刷的时候几乎不需要思考就写出来了。之前虽然也做出了O(N)的解法,但是写起来很痛苦,因为之前是靠着人类天生的智慧做题的,现在根据套路,也就是利用滑动窗口的思想来做就简单很多了。

       思想是维护一个滑动窗口,当遇到重复字符的时候,就把窗口首部调到上一次出现这个字符的下一个位置,始终维护一个满足条件的窗口。

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        if (!s.size()) return 0;
        int begin = 0;
        int res = 1;
        vector<int> last(256, -1);
        vector<bool> visit(256, false);
        unordered_set<int> unique;
        for (int i = 0; i < s.size(); i++)
        {
            if (!visit[s[i]])
            {
                visit[s[i]] = true;
            }
            else
            {
                for (int j = begin; j < last[s[i]]; j++)
                {
                    visit[s[j]] = false;
                }
                begin = last[s[i]] + 1;
            }
            res = max(res, i - begin + 1);
            last[s[i]] = i;

        }
        return res;
    }
};

 

[滑动窗口] leetcode 3 Longest Substring Without Repeating Characters

原文:https://www.cnblogs.com/fish1996/p/11302704.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!