76. Minimum Window Substring

题目描述

Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).

For example,
S = “ADOBECODEBANC”
T = “ABC”
Minimum window is “BANC”.

Note:
If there is no such window in S that covers all characters in T, return the empty string “”.

If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.

思路分析

这题同样是使用滑动窗口的思想,根据快慢指针来找到最小的字符串。去之前有区别的地方就是T中的字符串和S中的子串并不是按序对应,只要满足T中的字符在S中的某一子串中都存在即可。所以我们先用Map把T中的字符存下来,key对应字符,value对应个数。然后去S中找,出现相同个数字符的子串。
实践证明用map比较麻烦、改用数组、因为题目提示是字符,一般的字符或者符号都可以用ASCii码表示,ASCII 码使用指定的7 位或8 位二进制数组合来表示128 或256 种可能的字符。java中char类型可以自动转化为int,只要不超出可以表示的范围。设一个大小为256的数组,下标为字符的值,对应的值是字符的个数。

代码

public String minWindow(String s, String t) {
        if(s == null || t == null || s.length() < t.length()){
             return "";
        }
        int[] temp=new int[256];

        for (char c : t.toCharArray()) {
            temp[c]++;
        }
        int count = t.length(),minLen = Integer.MAX_VALUE,start=0,end=0,head=0;
        while(end<s.length())
        {
            if(temp[s.charAt(end++)]-->0)
            {
                count--;
            }
            //count=0,即S中存在子串覆盖了T中所有字符
            while(count==0)
            {
                if(end-start<minLen)
                {
                    minLen = end-start;
                    head = start;
                }

                //start向右移,使得其无法覆盖T中所有字符,寻找下一个可能项
                if(temp[s.charAt(start++)]++ == 0)
                {
                    count++;
                }
            }
        }
        return minLen == Integer.MAX_VALUE ? "" : s.substring(head, head+minLen);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值