leetcode: 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 emtpy string"".

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

解题思路:

  1. 这道题是一道典型的滑动窗口问题
  2. 我的解法是参考网上其他大佬的,所以具体看代码

代码如下:

    public String minWindow(String S, String T) {
        int [] map = new int[128];

	// 记录 T 中每个元素的个数
        for(int i = 0; i < T.length(); i++){
            map[T.charAt(i)]++;
        }

	// begin,end 两个指针指向窗口的首位, d 记录窗口的长度, count 记录 T 中还有几个字符没有被窗口包含
        int begin = 0,end = 0, d = Integer.MAX_VALUE, count = T.length(), head = 0;
        while(end < S.length()){
		
	    // map[] > 0 表示该字符在 T 中出现
            if(map[S.charAt(end++)]-- > 0){
                count--;
            }

	    // 当 count == 0 时,说明该窗口已经包含了 T 中所有的字符
	    // 记录当前窗口
            while(count == 0){
                if(end -begin < d){
                    d = end - (head = begin);
                }
		
		// 此时 begin 继续寻找其他可能的窗口
                if(map[S.charAt(begin++)]++ == 0 ){
                    count++;
                }
            }
        }
        return d == Integer.MAX_VALUE ? "" : S.substring(head,head + d);
    }

转载于:https://my.oschina.net/happywe/blog/3086503

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值