首页 > Windows开发 > 详细

LeetCode 76 Minimum Window Substring

时间:2014-11-26 16:33:12      阅读:432      评论:0      收藏:0      [点我收藏+]

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:"";
	}
}


LeetCode 76 Minimum Window Substring

原文:http://blog.csdn.net/mlweixiao/article/details/41516747

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!