LeetCode: Minimum Window Substring
来源:互联网 发布:淘宝店铺联盟怎么开通 编辑:程序博客网 时间:2024/06/10 14:56
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
class Solution {public: string minWindow(string S, string T) { int head = 0, back = 0, min = INT_MAX; string result = ""; map<char, int> counts; map<char, int> cur; int match = 0; for(int i = 0; i < T.size(); i++) { counts[T[i]]++; } for(int i = 0; i < S.size(); i++) { if(counts[S[i]] > 0) { cur[S[i]]++; if(cur[S[i]] <= counts[S[i]]) match++; if(match == T.size()) { while(counts[S[head]] <= 0 || cur[S[head]] > counts[S[head]]) { cur[S[head]]--; head++; } if(min > i-head+1) { min = i-head+1; result = S.substr(head, i-head+1); } cur[S[head]]--; match--; head++; } } } return result; }};
Round 2:
class Solution {public: string minWindow(string S, string T) { unordered_map<char, int> map; int min = INT_MAX; string result; for(int i = 0; i < T.size(); i++) { map[T[i]]++; } int match = 0, start = 0; for(int i = 0; i < S.size(); i++) { if(map.find(S[i]) != map.end()) { map[S[i]]--; if(map[S[i]] >= 0) { match++; } if(match == T.size()) { while(map.find(S[start]) == map.end() || map[S[start]] < 0) { if(map.find(S[start]) != map.end()) map[S[start]]++; start++; } if(i-start+1 < min) { min = i-start+1; result = S.substr(start, i-start+1); } map[S[start]]++; match--; start++; } } } return result; }};
0 0
- 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
- LeetCode:Minimum Window Substring
- hdu-1257
- 购房首付的和奋斗史
- ioctl 变成了 unlocked_ioctl
- 1>MSVCRTD.lib(MSVCR100D.dll) : error LNK2005: _strncmp 已经在 libcmtd.lib(strncmp.obj) 中定义
- MFC透明位图(2)--PNG的实现
- LeetCode: Minimum Window Substring
- Linux/Unix下pid文件作用浅析
- canvas基于页面宽度绘制饼图数据(适用与多屏幕适配开发)
- cannot convert parameter 2 from 'const char [12]' to 'LPCWSTR'
- 关于ansys里面的谐分析和瞬态分析结果的讨论
- c++自学 关于构造函数的基础
- Best Time to Buy and Sell Stock
- Java 创建Maven Web项目
- SQL Server存储过程 对数组参数的循环处理