[LeetCode] 76. Minimum Window Substring
来源:互联网 发布:淘宝 正义哥 编辑:程序博客网 时间:2024/06/14 03:55
[LeetCode] 76. 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.
要求在O(n)时间复杂度内,找出S字符串中包含T中所有字符的最短子字符串。
思路: 实在想不到。。。
参考并膜拜了超级大神的代码。
定义一个长度128(char的长度)的数组map,记录T中的字符和出现次数;同时初始化一个计数器cnt=T.length。
然后第一个指针end开始遍历S,遇到对出现的字符都在数组中-1计数,当遇到在T中的字符总计数器同时也-1,可以知道当cnt==0时,第一个匹配的S的子字符串已经出现了,这时另一个指针begin也开始遍历S,遇到对出现的字符都在数组中+1计数,当遇到T中的字符,总计数器+1,直到cnt!=0时又回到end指针,如此类推。
class Solution {public: string minWindow(string s, string t) { vector<int> ht(128, 0); // 整个char位的长度 int cnt = t.length(); int begin=0, end=0, min_len=INT_MAX, head=0; for (int i=0; i<cnt; ++i) { ++ht[t[i]]; } while (end < s.length()) { if (ht[s[end]] > 0) --cnt; --ht[s[end]]; ++end; while (cnt == 0) { if (min_len > end-begin) { min_len = end-begin; head = begin; } if (ht[s[begin]] == 0) ++cnt; ++ht[s[begin]]; ++begin; } } return min_len == INT_MAX ? "" : s.substr(head, min_len); }};
0 0
- LeetCode 76. Minimum Window Substring
- [LeetCode]76.Minimum Window Substring
- LeetCode 76.Minimum Window Substring
- LeetCode --- 76. Minimum Window Substring
- [Leetcode] 76. Minimum Window Substring
- [leetcode] 76.Minimum Window Substring
- **LeetCode 76. Minimum Window Substring
- leetcode 76. Minimum Window Substring
- 【LeetCode】76. Minimum Window Substring
- LeetCode 76. Minimum Window Substring
- Leetcode 76. Minimum Window Substring
- leetcode.76. Minimum Window Substring
- LeetCode 76. Minimum Window Substring
- [LeetCode] 76. Minimum Window Substring
- leetcode 76.Minimum Window Substring
- leetcode 76. Minimum Window Substring
- 76. Minimum Window Substring, leetcode
- leetcode-76. Minimum Window Substring
- iOS动态性(二)可复用而且高度解耦的用户统计埋点实现
- 3.文献检索
- Java 去除小数点后面多余的0
- 天创信用面试,公司网址:http://www.ypcredit.com/
- oracle数据库知识整理
- [LeetCode] 76. Minimum Window Substring
- vs2013安装openCV2.4.9时出现无法启动此程序,因为计算机中丢失opencv_core249d.dll
- Android退出应用程序的几种方式
- 一路风雪前行
- Dockerfile 命令
- 360度全景VR摄像机初探
- 反射(2)--Class类
- 【UE4学习】16_http访问PHP获得Json测试
- android studio 经纬度与百度地图拾取坐标经!纬!初入深坑!