码迷,mamicode.com
首页 > Windows程序 > 详细

Minimum Window Substring -- leetcode

时间:2015-04-13 09:42:33      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:leetcode   窗口   子串   最小   

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.


基本思路:

1. 维持一个窗口,使得[left, right] 包含子串T。

2. left尽可能向右靠近right,直到再多移动一步,窗口就不能包含字串T。

3. 在窗口向右滑动过程中,记录下最小的窗口。


class Solution {
public:
    string minWindow(string S, string T) {
        vector<int> modal(256);
        vector<int> actual(256);
        
        for (auto ch: T)
            ++modal[ch];
            
        int leftWnd = 0, rightWnd = S.size();
        int count = 0;
        for (int left = 0, right = 0; right < S.size(); ++right) {
            if (++actual[S[right]] <= modal[S[right]])
                ++count;
                
            if (count == T.size()) {
                while (!modal[S[left]] || actual[S[left]] > modal[S[left]])
                    --actual[S[left++]];
                
                if (right - left < rightWnd - leftWnd) {
                    rightWnd = right;
                    leftWnd = left;
                }
            }
        }
        
        if (count < T.size()) return "";
        
        return S.substr(leftWnd, rightWnd - leftWnd + 1);
    }
};


Minimum Window Substring -- leetcode

标签:leetcode   窗口   子串   最小   

原文地址:http://blog.csdn.net/elton_xiao/article/details/45013691

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!