剑指 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;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值