LeetcodeMinimum Window Substring

Posted wuezs

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetcodeMinimum 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;
	}


以上是关于LeetcodeMinimum Window Substring的主要内容,如果未能解决你的问题,请参考以下文章

LeetcodeMinimum Path Sum

LeetcodeMinimum Size Subarray Sum

dev tools杂谈

linux和window是文件挂载

ubuntu下linux常用指令总结

Window丢失api-ms-win-crt-runtime-l1-1-0.dll