【Leetcode】Minimum Window Substring

题目链接:https://leetcode.com/problems/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 empty string "".

If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.

思路:

时间太久 我也忘了咋做的了= =有时间再补

算法

	public String minWindow(String s, String t) {
		String result = "";
		StringBuffer res = new StringBuffer();
		HashMap<String, Integer> tm = new HashMap<String, Integer>();// 维护窗口内需要的t字符的个数,如果某字符值小于0表示该窗口有多于需要的字符个数
		int minLen = Integer.MAX_VALUE, start = 0, end = 0, size = t.length();// size
																				// 表示剩余要匹配t的字符个数

		for (int i = 0; i < t.length(); i++) { // 初始化
			String key = t.charAt(i) + "";
			if (tm.containsKey(key)) {
				tm.put(key, tm.get(key) + 1);
			} else {
				tm.put(key, 1);
			}
		}

		while (end < s.length()) {
			while (end < s.length() && size > 0) {
				String key = s.charAt(end) + "";
				if (tm.containsKey(key)) {
					if (tm.get(key) > 0) { // 如果需要该字符
						size--;
					}
					tm.put(key, tm.get(key) - 1);
				}
				res.append(key);
				end++;
			}// 已经找到一个window包含了t所有字符
			while (size == 0 && start < end) {
				if (minLen > end - start) { // 更新窗口大小
					minLen = end - start;
					result = s.substring(start, end);
				}
				String key = s.charAt(start) + "";
				if (tm.containsKey(key)) {
					if (tm.get(key) == 0) { // 如果窗口删除该字符,则跟t的匹配缺少该字符
						size++;
					}
					tm.put(key, tm.get(key) + 1);
					res.deleteCharAt(0);
				}
				start++;
			}
		}
		return result;
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值