首页 > 代码库 > Minimum Window Substring

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的窗口,逐步右移。使用begin和end来标记窗口的起始。
    public String minWindow(String S, String T) {
        if (S == null || T == null) {
        	return null;
        }
        if (T.equals("") || S.equals("")) {
        	return "";
        }
        Map<Character, Integer> needFind = new HashMap<Character, Integer>();
        Map<Character, Integer> hasFind = new HashMap<Character, Integer>();
        
        int lenS = S.length();
        int lenT = T.length();
        for (int i = 0; i < lenT; i++) {
        	char ch = T.charAt(i);
        	if (!needFind.containsKey(ch)) {
        		needFind.put(ch, 1);
        		hasFind.put(ch, 0);
        	} else {
        		needFind.put(ch, needFind.get(ch) + 1);
        	}
        }
        
        int newBegin = -1;
        int newEnd = S.length();
        int count = 0;
        for (int begin = 0, end = 0; end < lenS; end++) {
        	char ch = S.charAt(end);
        	if (needFind.containsKey(ch)) {
        		hasFind.put(ch, hasFind.get(ch) + 1);
        		if (hasFind.get(ch) <= needFind.get(ch)) {
        			count++;
        		}
        		if (count == lenT) {
        			char temp = S.charAt(begin);
        			while(!needFind.containsKey(temp) || hasFind.get(temp) > needFind.get(temp)) {
        				
        				if (needFind.containsKey(temp) && hasFind.get(temp) > needFind.get(temp)) {
        					hasFind.put(temp, hasFind.get(temp) - 1);
        				}
        				
        				begin = begin + 1;
        				temp = S.charAt(begin);
        			}
        			
        			if (end - begin < newEnd - newBegin) {
        				newEnd = end;
        				newBegin = begin;
        			}
        		}
        	}
        }
        
        if (newBegin == -1) {
        	return "";
        } else {
        	return S.substring(newBegin, newEnd + 1);
        }       
    }