您的位置:首页 > 其它

LeetCode Minimum Window Substring

2014-11-07 21:56 369 查看
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中所有字符,包括重复的字符。使用数组map记录T中每个字符的个数,数组sum记录S中start--end间的字符个数。
定义两个指针start和end,end往后移直到包含所有T中字符,start后压缩,直到不能压缩

判断是否比原来长度小,如果是则更新minstart、minend

end继续往后移,循环

public class Solution {
public String minWindow(String S, String T) {
int[] map = new int[256];
int[] sum = new int[256];
int lens = S.length();
int lent = T.length();
if (lent == 0 || lens == 0 || lent > lens)
return "";
int res = lens+1;
int start = 0, minstart = 0, minend = 0;
int num = 0;
Arrays.fill(map, 0);
Arrays.fill(sum, 0);
for (int i = 0; i < lent; i++) { //记录T中字符数
map[T.charAt(i)]++;
}
for (int i = 0; i < lens; i++) { //i即为end
if (map[S.charAt(i)] > 0) {
sum[S.charAt(i)]++; //记录start--i之间的字符数
if (sum[S.charAt(i)] <= map[S.charAt(i)])
num++;
if (num == lent) { //满足T中的所有字符要求
while (start < i) { //压缩start
if (map[S.charAt(start)] == 0) {
start++;
continue;
}
if (sum[S.charAt(start)] > map[S.charAt(start)]) {
sum[S.charAt(start)]--;
start++;
continue;
} else
break;
}
int count = i - start + 1; //计算长度
if (count < res) {
res = count;
minstart = start;
minend = i + 1;
}
}
}
}
return S.substring(minstart, minend);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息