76. Minimum Window Substring

problem:

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 empty string "".

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

这道题的要求是在给定的字符串S中找到最小的窗口使其完全包含字符串T中所有字符,如果不存在,则返回空串""

首先需要返回一个包含字符串中所有字符的窗口,其次这个窗口要最小。

1.返回一个window至少包含target中的所有字符

考虑到target中的string可能重复,所以使用一个hash来存储target中的string的分布情况。

2.在返回的window中,要尽可能地使得它最小。

所以就要尽可能地去掉不需要的部分,于是,对于每一个index结尾的窗口,看看它前面能丢掉多少个字符。丢掉的方式有两种,如果这个字符根本就不在needToFound中,那么可以丢掉,或者,如果这个字符在当前窗口中的数量超过了needToFound需要的数量,也可丢掉。

class Solution {
public:
    string minWindow(string s, string t) {
        int hasFound[256] = {0};
        int needToFind[256] = {0};
        int windowBegin = 0;
        int windowEnd = 0;
        int minwindowBegin = 0;
        int minWindowEnd = 0;
        //NOTE1: int minLength = S.length(); //minWindow("a", "a"): expected return "a", actual wrong answer "";
        int minLength = INT_MAX;
        string minStr = "";
        for (int i =0; i < t.length(); ++i){
            needToFind[t[i]]++;
        }

        int begin = 0, end = 0, count = 0;
        //string str1 = "ADOBECODEBANC";
        //string str2 = "ABC";
        for (begin = 0, end = 0; end < s.length();++end) {
            if (needToFind[s[end]]<0) continue;
                hasFound[s[end]]++;
            if (hasFound[s[end]] <= needToFind[s[end]])
                count++;
            if (count >= t.length()) {
                while (needToFind[s[begin]] == 0 || hasFound[s[begin]] > needToFind[s[begin]]) { //NOTE2: two level logica
                    if (hasFound[s[begin]] > needToFind[s[begin]]) {
                        hasFound[s[begin]]--;
                    }
                    begin++;
                }
                windowBegin = begin;
                windowEnd = end;
                if (windowEnd - windowBegin + 1 < minLength) {
                    minLength = windowEnd - windowBegin + 1;
                    windowEnd = end;
                    windowBegin = begin;
                    minStr = s.substr(windowBegin, windowEnd - windowBegin + 1);
                }
            }
        }
        return minStr;
    }
};


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值