LeetCode--Minimum Window Substring
来源:互联网 发布:淘宝号可以不实名认证 编辑:程序博客网 时间:2024/06/04 19:07
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.
思路:哈希表法。这里用两个数组tm和sm代替哈希表,首先统计T中每个字母的个数(可能一个字母有多个),然后开始滑动窗口,左端点起点为0,遍历右端点,如果遇到S中有T中的字母且个数不超过T中该字母的个数,则计数加1,直到计数达到T中字母个数,即S中窗口包含T为止,如果该窗口小于最小窗口长度,则更新最小窗口,同时左端点前移,如果左端点包含T中字母,则减去一个S中该字母的个数,若此时所需T中该字母个数不够,则计数减1,继续前移右窗口,滑动窗口直到结束。
class Solution {public: string minWindow(string S, string T) { if (T.size()>S.size()) return ""; string res=""; int left=0,count=0,minLen=S.size()+1; int tm[256]={0},sm[256]={0}; for(int i=0;i<T.size();i++) tm[T[i]]++; for(int right=0;right<S.size();right++){ if(tm[S[right]]){ sm[S[right]]++; if(sm[S[right]]<=tm[S[right]]) count++; while(count==T.size()){ if(right-left+1<minLen){ minLen=right-left+1; res=S.substr(left,minLen); } if(tm[S[left]]){ sm[S[left]]--; if(sm[S[left]]<tm[S[left]]) count--; } left++; } } } return res; }};
阅读全文
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
- onTouch onTouchEvent 与 onClick三者调用先后分析
- Ubuntu16.04配置ADB调试环境
- 破解IDEA2017
- iOS11 导航栏按钮位置问题的解决------新
- javaweb接口安全校验预备知识——spring 拦截器interceptor的使用
- LeetCode--Minimum Window Substring
- http://blog.csdn.net/anxpp/article/details/52108238
- asp.net如何上传文件(修改服务器来支持所有的文件格式)
- Linux下命令笔记
- PacketTooBigException: Packet for query is too large
- 【福利】3980元的Hadoop大数据视频教程限量领取!!!
- 解决libgtk2.0-dev依赖包的问题
- Logstash使用ruby和正则进行字符串处理
- 目录处理命令cd