美文网首页
最小覆盖子串

最小覆盖子串

作者: 啊磊11 | 来源:发表于2021-03-17 22:43 被阅读0次

     public String minWindow(String s, String t) {

            HashMap<Character,Integer> need = new HashMap();

            HashMap<Character,Integer> window = new HashMap();

            for(int i = 0;i<t.length();i++){

                int count = need.getOrDefault(t.charAt(i),0);

                need.put(t.charAt(i), count + 1);

            }

            int left = 0;

            int right = 0;

            int match = 0;

            int min = Integer.MAX_VALUE;

            int start = 0;

            while(right < s.length()){

                char c = s.charAt(right);

                right++;

                if(need.containsKey(c)){

                   int cou =  window.getOrDefault(c,0);

                   window.put(c,cou + 1);

                   if(window.get(c).equals(need.get(c))){

                       match++;

                   }

                }

                while(match == need.size()){

                    if((right - left) <min){

                        min = right - left;

                        start = left;

                    }

                    char d = s.charAt(left);

                    left++;

                    if(need.containsKey(d)){

                        int ccccc = window.get(d);

                        if(window.get(d).equals(need.get(d))){

                            match--;

                        }

                        window.put(d,ccccc-1);

                    }

                }

            }

            return min == Integer.MAX_VALUE? "":s.substring(start,start +min );

        }

    相关文章

      网友评论

          本文标题:最小覆盖子串

          本文链接:https://www.haomeiwen.com/subject/zdeycltx.html