20200406——第七十六题 最小覆盖字串

class Solution {
       public static String minWindow(String s, String t) {
        if(s == null || t== null||s.length() < t.length()){
            return "";
        }
        int[] window = new int[128];
        int[] needs = new int[128];
        for(int i = 0;i<t.length();++i){
            needs[t.charAt(i)]++;
        }
        int left = 0;
        int right = 0;
        String res = "";
        int minLength = s.length()+1;

        int count = 0;

        while (right < s.length()) {
            char ch = s.charAt(right);
            window[ch]++;
            if (needs[ch] > 0 && needs[ch] >= window[ch]) {
                count++;
            }

            //移动到不满足条件为止
            while (count == t.length()) {
                ch = s.charAt(left);
                if (needs[ch] > 0 && needs[ch] >= window[ch]) {
                    count--;
                }
                if (right - left + 1 < minLength) {
                    minLength = right - left + 1;
                    res = s.substring(left, right + 1);

                }
                window[ch]--;
                left++;

            }
            right++;

        }
        
        return res;
    }
}

在这里插入图片描述

发布了955 篇原创文章 · 获赞 43 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/qq_36344771/article/details/105347710
今日推荐