首页 > Windows开发 > 详细

Minimum Window Substring

时间:2015-07-02 02:13:46      阅读:190      评论: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.

?

import java.util.HashMap;

public class Solution {
    public String minWindow(String S, String T) {
	    String res = "";
	    if(S == null || T == null || S.length()==0 || T.length()==0) {
	    	return res;
	    }
	    HashMap<Character, Integer> dict = new HashMap<Character, Integer>();
	    for (int i = 0;i < T.length(); i++) {
	    	if (!dict.containsKey(T.charAt(i))) {
	    		dict.put(T.charAt(i), 1);
	    	} else {
	    		dict.put(T.charAt(i), dict.get(T.charAt(i))+1);
	    	}
	    }
	    int count = 0;
	    int pre = 0;
	    int minLen = S.length()+1;
	    for(int i = 0; i < S.length(); i++) {
	    	if (dict.containsKey(S.charAt(i))) {
	    		dict.put(S.charAt(i),dict.get(S.charAt(i))-1);
	    		if (dict.get(S.charAt(i)) >= 0) {
	    			count++;
	    		}
	    		while (count == T.length()) {
	    			if (dict.containsKey(S.charAt(pre))) {
	    				dict.put(S.charAt(pre),dict.get(S.charAt(pre))+1);
	    				if (dict.get(S.charAt(pre)) > 0) {
							if (minLen > i - pre + 1) {
								res = S.substring(pre, i + 1);
								minLen = i - pre + 1;
							}
							count--;
	    				}
	    			}
	    			pre++;
	    		}
	    	}
	    }
	    return res;
	}
}

?

Minimum Window Substring

原文:http://hcx2013.iteye.com/blog/2223392

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