leetcode 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).

Example:

Input: S = "ADOBECODEBANC", T = "ABC"
Output: "BANC"

Note:

  • If there is no such window in S that covers all characters in T, return the empty string "".
  • If there is such window, you are guaranteed that there will always be only one unique minimum window in S.

 

 

hard

class Solution {
    public String minWindow(String s, String t) {
        int[] map = new int[128];
        for(char c: t.toCharArray()) {
            map[c]++;
        }
        int count = t.length(), begin = 0, end = 0, d = Integer.MAX_VALUE, head = 0;
        
        while(end < s.length()){
            if(map[s.charAt(end)] > 0) {
                count--;
                
            }
            map[s.charAt(end)]--;
            end++;
            while(count == 0) {
                if(end - begin < d) {
                    d = end - begin;
                    head = begin;
                }
                if(map[s.charAt(begin)] == 0){
                    count ++;
                }
                map[s.charAt(begin)]++;
                begin++;
            }
            
        }
        return d == Integer.MAX_VALUE ? "" : s.substring(head, head+d);
    }
}

 

posted @ 2019-02-27 21:12  JamieLiu  阅读(144)  评论(0编辑  收藏  举报