[leetcode] Minimum Window Substring
来源:互联网 发布:玩天龙八部网络延迟 编辑:程序博客网 时间:2024/05/01 11:13
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.
原文链接:http://blog.csdn.net/jellyyin/article/details/10313827
思路:双指针,动态维护一个区间。尾指针不断往后扫,当扫到有一个窗口包含了所有T的字符后,然后再收缩头指针,直到不能再收缩为止。最后记录所有可能的情况中窗口最小的
代码:
class Solution {public: string minWindow(string S, string T) { int slen=S.size(); int tlen=T.size(); if(tlen>slen || tlen==0 || slen==0) return ""; int needFind[256]={0}; int hasFind[256]={0}; for(int i=0;i<tlen;i++){ needFind[T[i]]++; } int minLength=INT_MAX; int minbegin=0; int minend=slen-1; int begin=0; int end=0; for(int count=0;end<slen;end++){ if(needFind[S[end]]==0) continue; hasFind[S[end]]++; if(hasFind[S[end]]<=needFind[S[end]]) count++; if(count==tlen){ while(begin<end){ if(needFind[S[begin]]==0){ begin++; continue; } if(hasFind[S[begin]]>needFind[S[begin]]){ hasFind[S[begin]]--; begin++; continue; } else break; } int tempLength=end-begin+1; if(tempLength<minLength){ minbegin=begin; minend=end; minLength=tempLength; } } } if(minLength==INT_MAX) return ""; return S.substr(minbegin,minLength); }};
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
- 设计模式(三)--抽象工厂模式
- sdut 面向对象程序设计上机练习四(变量引用)
- 贡献式编程(一)
- jsp面试题
- 另5个你不知道的HTML5接口API
- [leetcode] Minimum Window Substring
- AFNetworking2.0源码解析<一>
- HTML5 Web Storage 特性
- hdoj 2102 A计划 【BFS】
- 安装内核模块的编译环境
- Android多媒体学习十三:检索MediaStore中的Video和其对应的缩略图信息
- Android 音频系统
- Android 中实现并发性、联网和数据访问
- Windows安装和使用zookeeper