Minimum Window Substring

本文详细阐述了如何使用双指针技术实现寻找字符串中最小包含特定子串的连续子序列,包括初始化计数器、遍历求解过程及优化时间空间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

思路:

两个指针控制,尾指针记录当前到了哪个位置,头指针记录当前识别的最小t的开始位置,通过控制头尾指针的移动标记最小window的位置。

时间复杂度O(N),空间复杂度O(1)。

class Solution {
public:
    string minWindow(string s, string t) {
        if(s.empty()) return "";
        if(s.size() < t.size()) return "";

        //hash table
        const int ASCII_MAX = 256;
        int appear_count[ASCII_MAX];
        int expect_count[ASCII_MAX];
        fill(appear_count, appear_count + ASCII_MAX, 0);
        fill(expect_count, expect_count + ASCII_MAX, 0);
        //initialize
        int minWidth = INT_MAX, min_start = 0;//window's size, starting point
        int wnd_start = 0;
        int appeared = 0;
        for(int i = 0; i < t.size(); ++i) {
            expect_count[t[i]]++;
        }

        for(int end = 0; end < s.size(); ++end) {
            if(expect_count[s[end]] > 0) {
                appear_count[s[end]]++;
                if(appear_count[s[end]] <= expect_count[s[end]]) {
                    appeared++;
                }
            }
            if(appeared == t.size()) {//find a complete t in s
                while(appear_count[s[wnd_start]] > expect_count[s[wnd_start]] || expect_count[s[wnd_start]] == 0) {
                    appear_count[s[wnd_start]]--;
                    wnd_start++;
                }
                if(minWidth > end - wnd_start + 1) {
                    minWidth = end - wnd_start + 1;
                    min_start = wnd_start;
                }
            }
        }

        if(minWidth == INT_MAX) return "";
        else return s.substr(min_start, minWidth);
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值