76. Minimum Window Substring 76.最小窗口子字符串BANC

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"



一句话概括思路:用map保证覆盖了t中所有的字母。
count = 0时,t全部找到,可以往前移。利用原来map的key,增加map,begin++
比如ABC全部找到,ABC得value减少为0.
此时再增加原来key的value,就ABC,因为这里就是曾经的end。end再从map中减去。

end - begin,在这个窗口的范围内覆盖了t的所有字母

 

map.containsKey(c) ){ //首先应该判断是否有这个key,然后才是 .get > 1

 

counter++; //counter重建了,所以需要数量++

 

begin++; //更新完了head = begin才加

 

class Solution {
    public String minWindow(String s, String t) {
        //cc
        if (s.length() < t.length())
            return "";
        
        //定义map
        HashMap<Character, Integer> map = new HashMap<>();
        int start = 0, end = 0, head = 0, len = Integer.MAX_VALUE;
        
        //定义counter
        for (char c : t.toCharArray()) {
            map.put(c, map.getOrDefault(c, 0) + 1);
        }
        int count = map.size();
        
        //while循环
        //end的减少
        while (end < s.length()) {
            char charAtEnd = s.charAt(end);
            if (map.containsKey(charAtEnd)) {
                map.put(charAtEnd, map.get(charAtEnd) - 1);
                
                if (map.get(charAtEnd) == 0)
                    count--;
            }
            end++;
            
            
            while (count == 0) {
                char charAtStart = s.charAt(start);
                if (map.containsKey(charAtStart)) {
                    map.put(charAtStart, map.get(charAtStart) + 1);
                
                if (map.get(charAtStart) > 0)
                    count++;
                }
                
                //更新head
                if (end - start < len) {
                    len = end - start;
                    head = start;
                }
                
                //start往前移
                start++;
            }
            
        }
        
        
        //返回
        if (len == Integer.MAX_VALUE) return "";
        else return s.substring(head, head + len);
    }
}
View Code

 

 
posted @ 2020-07-30 10:34  苗妙苗  阅读(119)  评论(0编辑  收藏  举报