76. 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.

---

Idea:

http://leetcode.com/2010/11/finding-minimum-window-in-s-which.html

check if count == T.length(), e.g. S="a", T="aa", expect rst="", if not check, rst="a"

O(N)

---

public class Solution {
    public String minWindow(String S, String T) {
        
        int[] hasFound = new int[256];
        int[] needToFind = new int[256];
        int count = 0;
        int minWindowLen = Integer.MAX_VALUE;
        int minWindowBegin = 0;
        int minWindowEnd = 0;
        
        for (int i = 0; i < T.length(); i++){
            needToFind[T.charAt(i)]++;
        }
    
    
        for (int begin = 0, end = 0; end < S.length(); end++) {
            
            int val = S.charAt(end);
            
            // skip characters not in T
            if (needToFind[val] == 0)   continue;
            
            hasFound[val]++;
            if (hasFound[val] <= needToFind[val])
                count++;
                
            // if window constraint is satisfied
            if (count == T.length()) {
                // advance begin index as far right as possible,
                // stop when advancing breaks window constraint.
                int sv = S.charAt(begin);
                while (needToFind[sv] == 0 || hasFound[sv] > needToFind[sv]) {
                    if (hasFound[sv] > needToFind[sv])
                      hasFound[sv]--;
                      begin++;
                      sv = S.charAt(begin);
                }
                
                // update minWindow if a minimum length is met
                int windowLen = end - begin + 1;
                if (windowLen < minWindowLen) {
                    minWindowBegin = begin;
                    minWindowEnd = end;
                    minWindowLen = windowLen;
                }
            } // end if
        } // end for
        
        
        // check the length!!!!!!!
        if(count == T.length())
            return S.substring(minWindowBegin,minWindowEnd+1);
        else
            return new String();
        
    }
}

 

posted @ 2013-09-15 07:22  LEDYC  阅读(197)  评论(0)    收藏  举报