LeetCode OJ 之 Minimum Window Substring (最小窗口子串)

本文介绍了一种在字符串S中寻找包含字符串T所有字符的最小子串的算法,时间复杂度为O(n)。通过使用双指针技术,动态维护一个包含T中所有字符的最短区间。

题目:

Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).

For example,
S = "ADOBECODEBANC"
T = "ABC"

Minimum window is "BANC".

Note:
If there is no such window in S that covers all characters in T, return the emtpy string "".

If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.

给定字符串S和T,在S中找出最小的窗口包含T中所有的字符。时间复杂度为O(n)。

注意:

如果找不到包含T中所有的字符,返回空串。

如果有多个这样的窗口,确保返回唯一的最小窗口。

思路:

双指针,动态维护一个区间。尾指针不断往后扫,当扫到有一个窗口包含了所有T 的字符后,然后再收缩头指针,直到不能再收缩为止。最后记录所有可能的情况中窗口最小的.

代码:

class Solution {
public:
    string minWindow(string S, string T) 
    {
        if(S.empty() || S.size() < T.size())
            return "";
        int appeared_count[256] = {0};
        int expected_count[256] = {0};//数组记录T中相应字符出现的次数,比如字符串"aabb",expected_count[97] = 2,expected_count[98] = 2,类似于哈希表,键表示字符,值表示字符出现的次数
        for(int i = 0 ; i < T.size() ; i++)
            expected_count[T[i]]++;
        int minWidth = INT_MAX , min_start = 0;//minWidth记录最小窗口的长度,min_start记录最小窗口的起始位置
        int wnd_start = 0;//当前窗口的起始位置
        int appeared = 0;//appeared记录S中出现的T中的字符的个数,当appeared==T.size()时,说明找到一个符合条件的
        for(int wnd_end = 0 ; wnd_end < S.size() ; wnd_end++)
        {
            if(expected_count[S[wnd_end]] > 0)
            {
                appeared_count[S[wnd_end]]++;
                if(appeared_count[S[wnd_end]] <= expected_count[S[wnd_end]])
                    appeared++; //当字符S[wnd_end]出现的次数不大于T中出现次数时,appeared才++
            }
            if(appeared == T.size())
            {
                while(appeared_count[S[wnd_start]] > expected_count[S[wnd_start]] || 
                expected_count[S[wnd_start]] == 0)
                {
                    appeared_count[S[wnd_start]]--;
                    wnd_start++;
                }
                if(minWidth > (wnd_end - wnd_start + 1))
                {
                    minWidth = wnd_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、付费专栏及课程。

余额充值