首页 > Windows开发 > 详细

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

时间:2020-06-08 22:37:01      阅读:55      评论:0      收藏:0      [点我收藏+]

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)

 

技术分享图片
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.最小窗口子字符串

原文:https://www.cnblogs.com/immiao0319/p/13068736.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!