Minimum Window Substring
Apr 15 '12
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.
1st try. not linear time.
public class Solution {
public String minWindow(String S, String T) {
// Start typing your Java solution below
// DO NOT write main() function
if( T==null || T.length()==0 ) return "";
if( S==null || S.length()<T.length() ) return "";
int ssz = S.length();
int tsz = T.length();
Map<Character, Integer> map = new HashMap<Character, Integer>();
for(int i=0; i<tsz; i++) {
char c = T.charAt(i);
if(map.containsKey(c)) {
map.put(c, map.get(c)+1);
} else {
map.put(c, 1);
}
}
for(int i=tsz; i<=ssz; i++){
for(int j=0; j<=ssz-i; j++) {
Map<Character, Integer> temp = new HashMap<Character, Integer>(map);
for(int k=0; k<i;k++) {
char c = S.charAt(j+k);
if(temp.containsKey(c)) {
if(temp.get(c)==1) {
temp.remove(c);
} else {
temp.put(c, map.get(c)-1);
}
}
}
if(temp.isEmpty()) return S.substring(j,j+i);
}
}
return "";
}
}