Minimum Window Substring

http://www.ninechapter.com/solutions/minimum-window-substring/
http://blog.csdn.net/linhuanmars/article/details/20343903

//redo 3/31
public class Solution {
    public String minWindow(String S, String T) {
        if(S == null || T == null){
            return "";
        }
        if(S.length() == 0 || T.length() == 0){
            return "";
        }
        HashMap<Character, Integer> freq = new HashMap<Character, Integer>();
        for(int i = 0; i < T.length(); i++){
            char c = T.charAt(i);
            if(!freq.containsKey(c)){
                freq.put(c, 1);
            }else{
                freq.put(c, freq.get(c) + 1);
            }
        }
        HashMap<Character, Integer> counter = new HashMap<Character, Integer>();
        String res = "";
        int left = 0, matches = 0;
        for(int i = 0; i < S.length(); i++){
            char c = S.charAt(i);
            if(!freq.containsKey(c)) continue;
            else{
                if(!counter.containsKey(c)){
                    counter.put(c, 1);
                }else{
                    counter.put(c, counter.get(c) + 1);
                }
            }
            if(counter.get(c) <= freq.get(c)){
                matches++;
            }
            if(matches == T.length()){
                while(left < S.length()){
                    char ch = S.charAt(left);
                    if(!freq.containsKey(ch)){
                        left++;
                        continue;
                    }
                    if(counter.get(ch) > freq.get(ch)){
                        left++;
                        counter.put(ch, counter.get(ch) - 1);
                        continue;
                    }
                    break;
                }
                if(res.length() == 0 || i - left + 1 < res.length()){ //bug here first time 
                    res = S.substring(left, i + 1);
                }
            }
        }
        return res;
        
    }
}


Leave a comment