滑动窗口模版-字母数字版

public class Solution {
public String minWindow(String s, String t) {
    if(s == null || s.length() < t.length() || s.length() == 0){
        return "";
    }
    HashMap<Character,Integer> map = new HashMap<Character,Integer>();
    //把target的字母存到map
    for(char c : t.toCharArray()){
        if(map.containsKey(c)){
            map.put(c,map.get(c)+1);
        }else{
            map.put(c,1);
        }
    }
    int left = 0;
    int minLeft = 0;
    int minLen = s.length()+1;
    int count = 0;
    for(int right = 0; right < s.length(); right++){
        //如果map中包括了s的字母,就逐个减去
        if(map.containsKey(s.charAt(right))){
            map.put(s.charAt(right),map.get(s.charAt(right))-1);
            //同时用count统计相同字母的个数
            if(map.get(s.charAt(right)) >= 0){
                count ++;
            }
            //count凑够了t
            while(count == t.length()){
                //greedy更新结果字符串的长度
                if(right-left+1 < minLen){
                    minLeft = left;
                    minLen = right-left+1;
                }
                //s的left如果已经出现了,就count减去它,同时更新left
                if(map.containsKey(s.charAt(left))){
                    map.put(s.charAt(left),map.get(s.charAt(left))+1);
                    if(map.get(s.charAt(left)) > 0){
                        count --;
                    }
                }
                left ++ ;
            }
        }
    }
    if(minLen>s.length())  
    {  
        return "";  
    }  
    
    return s.substring(minLeft,minLeft+minLen);
}
}

 

posted @ 2023-01-29 01:35  苗妙苗  阅读(19)  评论(0编辑  收藏  举报