LEETCODE: Minimum Window Substring

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.


直接上代码吧,其实就是先找到包含所有字符的,然后看看最左边那些是不是想要的,如果不是就去掉,看看新的长度是不是最短的。是最短的,就记下来。然后,把头上那个去掉,继续查找。


class Solution {
public:
    string minWindow(string S, string T) {
        vector<int> existing(256, 0);
        vector<int> expected(256, 0);
        int leftmost = 0;
        int substrstart = -1;
        int substrlength = 0x7fffffff;
        int basepointer = 0;
        
        int lack = T.size();
        // Initialize the count array to count all characters in T.
        for(int ii = 0; ii < T.size(); ii ++)
            expected[T[ii]] ++;
            
        for(int ii = 0; ii < S.size(); ii ++) {
            // If the current character is in T, and occurs less than expected.
            if(existing[S[ii]] < expected[S[ii]])
                lack --;
                
            // Record the current character.
            existing[S[ii]] ++;
            
            // If all characters in T have all show up.
            if(lack == 0) {
                // Remove characters that existing on the left edge of the sub string.
                while(existing[S[basepointer]] > expected[S[basepointer]]) {
                    existing[S[basepointer]] --;
                    basepointer ++;
                }
                
                // Get the new length if curent one is shorter.
                if(substrlength > ii - basepointer + 1) {
                    substrlength = ii - basepointer + 1;
                    substrstart = basepointer;
                }
                
                while(lack == 0) {
                    // Remove the character on the left edge and set new condition for loop.
                    existing[S[basepointer]] --;
                    if(existing[S[basepointer]] < expected[S[basepointer]]) {
                        lack ++;
                    }
                    basepointer ++;
                }

            }
        }
        return substrstart == -1 ? "" : S.substr(substrstart, substrlength);
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值