Tuesday, December 16, 2014

Minimum Window Substring

Q:
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.

T:
We need two hashmap. One hashmap stores the number of each character in T. The other hashmap stores the number of character seen in S currently. We use to pointers to calculate the window. The end pointer traverse S and keeps updating the hashmap. If a character occurs less than it's in T, increase the number of characters that is valid for matching T. Once the number equals to T's size, we move the start pointer forward as long as there are more number of characters in current window than in T. By this, we can get the valid windows. Once we get a window, we record it if its length is smaller than previous window.

A:


class Solution {
public:
    string minWindow(string S, string T) {
        unordered_map< char, int > snum;
        unordered_map< char, int > tnum;
        for(int i=0; i < T.size(); i++) {
            tnum[T[i]]++;
        }
        string ret = "";
        int match = 0;
        int start = 0;
        int end = 0;
        for(end=0; end < S.size(); end++) {
            snum[S[end]]++;
            if(snum[S[end]] <= tnum[S[end]]) {
                match++;
            }
            if(match == T.size()) {
                while(snum[S[start]] > tnum[S[start]]) {
                    snum[S[start]]--;
                    start++;
                }
                if(ret.size()==0 || ret.size() > end-start+1) {
                    ret = S.substr(start, end-start+1);
                }
                snum[S[start]]--;
                start++;
                match--;
            }
        }
        return ret;
    }
};

No comments:

Post a Comment