LeetCode Minimum Window Substring

来源:互联网 发布:淘宝客服数据报表 编辑:程序博客网 时间:2024/06/06 07:02

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即为endif (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) {   //压缩startif (map[S.charAt(start)] == 0) {   start++;continue;}if (sum[S.charAt(start)] > map[S.charAt(start)]) {sum[S.charAt(start)]--;start++;continue;} elsebreak;}int count = i - start + 1;  //计算长度if (count < res) {res = count;minstart = start;minend = i + 1;}}}}return S.substring(minstart, minend);    }}


0 0
原创粉丝点击