LeetCode Minimum Window Substring

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);
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值