LeetCode[Hash Table]: Minimum Window Substring
来源:互联网 发布:网络手机高清直播软件 编辑:程序博客网 时间:2024/06/08 03:06
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.
对于这个题目,我毫无头绪,当我在Discuss上看懂这个解法的时候:https://oj.leetcode.com/discuss/10337/accepted-o-n-solution我觉得这个解法实在是太妙了!这个链接有关于这个解法的idea:https://oj.leetcode.com/discuss/5469/is-the-length-of-t-considered-constant-or-m
下面先贴出这个解法的代码:
string minWindow(string S, string T) { int count = T.size(); int require[128] = { 0 }; bool charSet[128] = { false }; for (int n = 0; n < count; ++n) { require[T[n]]++; charSet[T[n]] = true; } int i = -1, j = 0; int minLen = INT_MAX, minIdx = 0; while (i < (int)S.size() && j < (int)S.size()) { if (count) { i++; require[S[i]]--; if (charSet[S[i]] && require[S[i]] >= 0) count--; } else { if (minLen > i - j + 1) { minLen = i - j + 1; minIdx = j; } require[S[j]]++; if (charSet[S[j]] && require[S[j]] > 0) count++; j++; } } return (minLen == INT_MAX ? "" : S.substr(minIdx, minLen)); }
直观地理解这个算法是比较困难的,建议用一些例子跑起来,这样会比较容易理解这个算法为什么能到期望的目的。总之我很为这个解法而惊叹!
这个算法的时间性能表现如下图所示:
- LeetCode[Hash Table]: Minimum Window Substring
- LeetCode: Minimum Window Substring
- LeetCode Minimum Window Substring
- LeetCode : Minimum Window Substring
- [LeetCode] Minimum Window Substring
- [Leetcode] Minimum Window Substring
- LeetCode: Minimum Window Substring
- [LeetCode]Minimum Window Substring
- [leetcode]Minimum Window Substring
- Leetcode:Minimum Window Substring
- LeetCode-Minimum Window Substring
- [leetcode] Minimum Window Substring
- [leetcode] Minimum Window Substring
- leetcode Minimum Window Substring
- [LeetCode] Minimum Window Substring
- [LeetCode] Minimum Window Substring
- leetcode minimum window substring
- LeetCode - Minimum Window Substring
- android开发之为何图片模糊显示情况之一
- Objective-C中的浅拷贝和深拷贝
- (一)UI设计的一些常识
- 基础练习 字母图形
- hdu2574 Hdu Girls' Day
- LeetCode[Hash Table]: Minimum Window Substring
- 算法竞赛入门经典第一、二章摘记
- iOS-基本数据类型-NSArray/NSMutableArray
- UVa 11752 The Super Powers(数学)
- Web开发中XML概述
- jqmPhp – jQuery Mobile项目的HTML代码生成器
- js得到昨天的时间
- python 学习笔记 UDP
- 通配符&正则表达式