高频刷题-滑动窗口(Sliding Window)专题

滑动窗口算法常用于数组、字符串和链表中处理连续子问题,将多重循环转化为单循环,提高效率。文章介绍了算法原理,提供了一个非固定大小窗口的模板,并通过LeetCode题目实例讲解如何应用该算法,包括查找所有回文子串、找到包含目标字符的最小子串及求无重复字符的最长子串等问题。此外,还讨论了使用数组存储字符计数以优化时间复杂度的方法。
摘要由CSDN通过智能技术生成

       滑动窗口算法多用于处理数组(Array), 字符串(String)或者链表(LinkedList)中关于子字符串(Substrings), 子数组(Subarrays, Sublists)等连续问题。该算法可以将多重嵌套的循环转化为单循环,从而降低时间复杂度(O(n))。滑动窗口是同向双指针的一个类型。

注意上述的滑动窗口示意图是固定大小,而现实中窗口大小也可以是不固定的。

下面给出滑动窗口算法的一个模板,来源于leetcode并做了一些理解上的修改。注意模板给出的是一个非固定大小窗口的模板,关键步骤都已经注释了。

来源于: https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/92007/sliding-window-algorithm-template-to-solve-all-the-leetcode-substring-search-problem

public static List<Integer> slidingWindowTemplate(String s, String t) {
        // 初始化返回结果的集合
        List<Integer> result = new LinkedList<>();
        if (t.length() > s.length()) return result;

        //创建一个hashmap去保存目标字符串的子字符
        //(K, V) = (字符, 字符出现的频率)
        Map<Character, Integer> tmap = new HashMap<>();
        for (char c : t.toCharArray()) {
            tmap.put(c, tmap.getOrDefault(c, 0) + 1);
        }
        //维持一个counter去检查是否已经匹配了目标字符串.
        int counter = tmap.size();  //must be the tmap size, NOT the string size because the char may be duplicate.

        //Two Pointers: left - left pointer of the window; right - right pointer of the window
        int left = 0, right = 0;
//
//        //the length of the substring which match the target string.
//        int len = Integer.MAX_VALUE;

        // 查找直到左侧指针已经移动到最后一个字符
        while (right < s.length()) {

            char c = s.charAt(right);//get a character

            if (tmap.containsKey(c)) {
                tmap.put(c, tmap.get(c) - 1);// 找到一个字符就 - 1
                if (tmap.get(c) == 0) counter--;  // 该字符减小到符合要求,整个counter
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值