From e6cf2507e09a89a6f24b102fd5eb68cc58981a16 Mon Sep 17 00:00:00 2001 From: CodingGorit <5571237+CodingGorit@user.noreply.gitee.com> Date: Fri, 15 Mar 2024 02:21:43 +0000 Subject: [PATCH] Author: CodingGorit. Commit Date: 2024/03/15. Commit Type: leetcode 076. Commit Description: solve the leetcode 076 of minimum-window-substring. Signed-off-by: CodingGorit <5571237+CodingGorit@user.noreply.gitee.com> --- .../076 minimum-window-substring/index.ts | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/leetcode-coding/leetcode/076 minimum-window-substring/index.ts b/leetcode-coding/leetcode/076 minimum-window-substring/index.ts index 9655574..d8e5896 100644 --- a/leetcode-coding/leetcode/076 minimum-window-substring/index.ts +++ b/leetcode-coding/leetcode/076 minimum-window-substring/index.ts @@ -82,3 +82,57 @@ function minWindow(s: string, t: string): string { return s.slice(begin, begin + minLen + 1); // Include the end character in the result } + +function minWindow_two(s: string, t: string): string { + // 验证输入参数 + if (s.length === 0 || t.length === 0) { + return ""; + } + // 使用哈希表记录t中每个字符的出现次数 + const targetCounts: Record = {}; + for (let char of t) { + targetCounts[char] = (targetCounts[char] || 0) + 1; + } + // 初始化窗口起始位置和最小子串的起始位置 + let start = 0, + end = 0, + minLength = Infinity, + validWindowStart = 0, + validCount = t.length; + + while (end < s.length) { + const currentChar = s[end]; + if (targetCounts[currentChar] !== undefined) { + // 当前字符是目标字符之一,则目标字符计数减一 + targetCounts[currentChar]--; + // 如果当前字符计数 >= 0,说明当前窗口包含了该字符所需的全部实例 + if (targetCounts[currentChar] >= 0) { + validCount--; + } + } + // 当窗口包含了t中所有字符时,尝试缩小窗口 + while (validCount === 0) { + // 更新最小子串长度和起始位置 + if (end - start + 1 < minLength) { + minLength = end - start + 1; + validWindowStart = start; + } + const startChar = s[start]; + if (targetCounts[startChar] !== undefined) { + // 当前窗口包含的实例数过多,需要移除一个 + targetCounts[startChar]++; + // 如果移除后该字符计数 > 0,说明当前窗口多了一个该字符实例 + if (targetCounts[startChar] > 0) { + validCount++; + } + } + // 缩小窗口 + start++; + } + // 扩展窗口 + end++; + } + + // 如果没有找到有效子串,返回空字符串 + return minLength === Infinity ? "" : s.substr(validWindowStart, minLength); +} \ No newline at end of file -- Gitee