首页 > Windows开发 > 详细

Minimum Window Substring -- leetcode

时间:2015-04-13 09:39:19      阅读:326      评论:0      收藏:0      [点我收藏+]

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!