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
public class Solution {
public String minWindow(String S, String T) {
if(S==null || T==null || S.length()<T.length()) {
return "";
}
HashMap<Character, Integer> needFind = new HashMap<Character, Integer>();
HashMap<Character, Integer> alreadyFind = new HashMap<Character, Integer>();
for(int i=0;i<T.length();i++) {
char c = T.charAt(i);
alreadyFind.put(c, 0);
if(needFind.containsKey(c)) {
needFind.put(c, needFind.get(c) + 1);
} else {
needFind.put(c, 1);
}
}
int minStart = -1;
int minEnd = S.length();
int start = 0;
int len = 0;
for (int i = 0; i < S.length(); i++) {
char c = S.charAt(i);
if(needFind.containsKey(c)) {
if(alreadyFind.get(c) < needFind.get(c)) {
len++;
}
alreadyFind.put(c, alreadyFind.get(c) + 1);
if(len==T.length()) {
while(true) {
if(!needFind.containsKey(S.charAt(start))) {
start++;
} else {
if(alreadyFind.get(S.charAt(start))>needFind.get(S.charAt(start))) {
alreadyFind.put(S.charAt(start), alreadyFind.get(S.charAt(start))-1);
start++;
} else {
break;
}
}
}
if(i-start<minEnd-minStart) {
minStart = start;
minEnd = i;
}
}
}
}
if(minStart==-1) {
return "";
} else {
return S.substring(minStart, minEnd + 1);
}
}
}
==========
public class Solution {
public String minWindow(String s, String t) {
if(s == null || t == null || t.length() > s.length()) {
return "";
}
int[] remaining = new int[128];
int required = t.length();
int min = s.length() + 1, start = 0, left = 0;
for (int i = 0; i < t.length(); i++){
remaining[t.charAt(i)]++;
}
int i = 0;
while (i <= s.length() && start < s.length()){
if (required > 0){
if (i == s.length()) {
break;
}
remaining[s.charAt(i)]--;
if (remaining[s.charAt(i)] >= 0) {
required--;
}
i++;
}
if (required == 0) {
if (i - start < min) {
min = i - start;
left = start;
}
remaining[s.charAt(start)]++;
if (remaining[s.charAt(start)] > 0) {
required++;
}
start++;
}
}
return min == s.length() + 1 ? "" : s.substring(left, left + min);
}
}
没有评论:
发表评论