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

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"

就是在模板的基础上,先得赋值给head。求出字符串长度
if (end - begin < len) {
                    len = end - begin;
                    head = begin;
                }

再用一下substring就行了

s.substring(head, head+len)

 

76. Minimum Window Substring 76.最小窗口子字符串
public class Solution {
    public String minWindow(String s, String t) {
        List<Integer> result = new LinkedList<>();
        if(t.length()> s.length()) return "";
        Map<Character, Integer> map = new HashMap<>();
        
        for(char c : t.toCharArray()){
            map.put(c, map.getOrDefault(c, 0) + 1);
        }
        int counter = map.size();
        
        int begin = 0, end = 0;
        int head = 0;
        int len = Integer.MAX_VALUE;
        
        
        while(end < s.length()){
            char c = s.charAt(end);
            if( map.containsKey(c) ){
                map.put(c, map.get(c)-1);
                if(map.get(c) == 0) counter--;
            }
            end++;
            
            while(counter == 0){
                char tempc = s.charAt(begin);
                if(map.containsKey(tempc)){
                    map.put(tempc, map.get(tempc) + 1);
                    if(map.get(tempc) > 0){
                        counter++;
                    }
                }
                
                if (end - begin < len) {
                    len = end - begin;
                    head = begin;
                }

                begin++;
            }
            
        }
        
        //cc
        if (len == Integer.MAX_VALUE) return "";
        return s.substring(head, head + len);
    }
}
View Code

 

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

上一篇:Photoshop艺术处理婚纱照效果


下一篇:laravel 5.6 API 接口开发限制接口访问频率