剑指 Offer II 017. 含有所有字符的最短字符串(Java)

public static String minWindow(String s, String t) {
        int[] s1 = new int[52];
        int[] t1 = new int[52];
        if (s.length() < t.length()) return "";
        for (int i = 0; i < t.length(); i++) {
            if (t.charAt(i)>='a'&&t.charAt(i)<='z') t1[t.charAt(i)-'a']++;
            if (t.charAt(i)>='A'&&t.charAt(i)<='Z') t1[t.charAt(i)-'A'+26]++;
            if (s.charAt(i)>='a'&&s.charAt(i)<='z') s1[s.charAt(i)-'a']++;
            if (s.charAt(i)>='A'&&s.charAt(i)<='Z') s1[s.charAt(i)-'A'+26]++;
        }
        if (Arrays.equals(s1,t1)) return s.substring(0,t.length());
        int minLen = 999999999;
        int start = 0,end = 0;
        int st=0,en=0;
        for (int i = t.length();i < s.length();i++){
            if (s.charAt(i)>='a'&&s.charAt(i)<='z') s1[s.charAt(i)-'a']++;
            if (s.charAt(i)>='A'&&s.charAt(i)<='Z') s1[s.charAt(i)-'A'+26]++;
            if (check(s1,t1)){
                end = i+1;
                if (end-start<minLen){
                    minLen = end-start;
                    st = start;
                    en = end;
                }
                for (int j = start; j < end; j++) {
                    if (s.charAt(j)>='a'&&s.charAt(j)<='z') s1[s.charAt(j)-'a']--;
                    if (s.charAt(j)>='A'&&s.charAt(j)<='Z') s1[s.charAt(j)-'A'+26]--;
                    if (!check(s1,t1)){
                        start = j+1;
                        break;
                    }else{
                        start++;
                        if (end-start<minLen){
                            minLen = end-start;
                            st = start;
                            en = end;
                        }
                    }
                }
            }
        }
        if (st == 0 && en == 0) return "";
        return s.substring(st,en);
    }
    public static boolean check(int[] s1,int[] t1)
    {
        for (int i = 0; i < 52; i++) {
            if (s1[i] < t1[i]){
                return  false;
            }
        }
        return true;
    }

你可能感兴趣的:(力扣刷题,算法,数据结构)