Finley.Hamilton 发表于3年前

• 发表于 3年前
• 阅读 119
• 收藏 3
• 评论 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.

# 代码

``````public class Solution {
Map<Character, Integer> map = new HashMap<Character, Integer>();

public String minWindow(String S, String T) {
int i = 0;
int j = 0;

int[] count = new int[128];
int minWindows = Integer.MAX_VALUE;
String minWindowString="";

for (char c : T.toCharArray()) {
if (!map.containsKey(c)) {
map.put(c, 0);
}
map.put(c, map.get(c) + 1);
}

for (; j < S.length(); j++) {
if (contain(count, T)) {
for (; i <= j; i++) {
if (!contain(count, T)) {
break;
} else {
if(minWindows > j-i) {
minWindows = j-i;
minWindowString = S.substring(i,j);
}

}
// contains i in this iteration
count[S.charAt(i)]--;
}
}
// do not contains j in this iteration
count[S.charAt(j)]++;
}

for (; i < j; i++) {
if (!contain(count, T)) {
break;
} else {
if(minWindows > j-i) {
minWindows = j-i;
minWindowString = S.substring(i,j);
}
}
count[S.charAt(i)]--;
}

// System.out.println(minWindowString);
if (i == 0) {
return "";
}
return minWindowString;
}

private boolean contain(int[] count, String t) {
for (char character : map.keySet()) {
if (count[character] < map.get(character)) {
return false;
}
}
return true;
}
}
``````

Finley.Hamilton

×