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

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

思路:双指针,动态维护一个区间。尾指针不断往后扫,当扫到有一个窗口包含了所有T的字符后,然后再收缩头指针,直到不能再收缩为止,当找到一个之后,需要将头指针存储起来,从而下一次头指针还是从原来的头指针开始的。
public class Solution {
	public String minWindow(String S, String T) {
		if (S == null || S.length() == 0) {
			return S;
		}
		if (T == null || T.length() == 0) {
			return "";
		}

		HashMap<Character, Integer> tCounter = new HashMap<Character, Integer>();
		Character c;
		for (int i = 0; i < T.length(); i++) {
			c = T.charAt(i);
			if (tCounter.containsKey(c)) {
				tCounter.put(c, tCounter.get(c) + 1);
			} else {
				tCounter.put(c, 1);
			}
		}
		HashMap<Character, Integer> minWindowCounter = new HashMap<Character, Integer>();
		String minWindow = null;
		int tCount = T.length();
		int begin = 0, end = 0,temp=0;
		for (end = 0; end < S.length(); end++) {
			c = S.charAt(end);
			if (!tCounter.containsKey(c)) {
				continue;
			}
			if(minWindowCounter.containsKey(c)){
				minWindowCounter.put(c, minWindowCounter.get(c) +1);
			}else {
				minWindowCounter.put(c,  1);
			}
			if (minWindowCounter.get(c) <=tCounter.get(c)) {
				tCount--;
			}
			
			if (tCount == 0) {
				for (begin = temp; begin <= end; begin++) {
					c = S.charAt(begin);
					if (!tCounter.containsKey(c)) {
						continue;
					}
					if (minWindowCounter.get(c) <=tCounter.get(c)) {//头指针不能再收缩了
						temp=begin;
						if(minWindow==null||end+1-begin<minWindow.length()){
							minWindow = S.substring(begin, end + 1);
						}
						break;
					}else{
						minWindowCounter.put(c, minWindowCounter.get(c)-1);
					}
				}
			}	
		}
		return minWindow!=null?minWindow:"";
	}
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值