[Leetcode] Minimum Window Substring (Java)

最小覆盖子串算法
本文介绍了一种在字符串S中寻找包含字符串T所有字符的最小子串的方法,并提供了一个复杂度为O(n)的解决方案。该算法使用双指针技术(start和end),通过不断移动end指针来尝试覆盖T的所有字符,一旦覆盖则开始移动start指针以缩小窗口,直至找到最短的有效子串。

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.

在S中找到包含T所有字符的最小窗口(类似于文本摘要提取)

用两个指针:start、end

1)若未包含所有字符,则end++;

2)若包含所有字符,则start++,直到不包含为止,得到窗口大小并与当前最小窗口比较并更新。

public class Solution {
    public String minWindow(String S, String T) {
		int min = S.length()+1;
		int minStart = 0;
		boolean flag = false;
		int count=T.length();
		int[] count1 = new int[256];
		Map<Character, Boolean> map = new HashMap<Character, Boolean>();
		int start=0,end=0;
		for(int i=0;i<T.length();i++){
			count1[T.charAt(i)]++;
			map.put(T.charAt(i), true);
		}
		for(end=0;end<S.length();end++){
			if(map.containsKey(S.charAt(end))&&map.get(S.charAt(end))){
				count1[S.charAt(end)]--;
				if(count1[S.charAt(end)]>=0){
					count--;
				}
			}
			if(count==0){
				while(count==0){
					if(map.containsKey(S.charAt(start))&&map.get(S.charAt(start))){
						count1[S.charAt(start)]++;
						if(count1[S.charAt(start)]>0)
							count++;
					}
					start++;
				}
				if(end-start+2<min){
					min=end-start+2;
					minStart=start-1;
				}
			}
		}
		if(min==S.length()+1)
			return "";
    	return S.substring(minStart,minStart+min);
    }
}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值