[LeetCode]Minimum Window Substring
2014-01-14 22:19
393 查看
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 =
T =
Minimum window is
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.
思考:虽然也想到了时间换空间的方法,但是时间复杂度还是不能压到O(n)。我的思路是二维数组记录T中每个字符的index,然后转化为一个求最短距离。
参考:http://discuss.leetcode.com/questions/97/minimum-window-substring
此方法的精妙之处在于count!
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.
思考:虽然也想到了时间换空间的方法,但是时间复杂度还是不能压到O(n)。我的思路是二维数组记录T中每个字符的index,然后转化为一个求最短距离。
参考:http://discuss.leetcode.com/questions/97/minimum-window-substring
此方法的精妙之处在于count!
class Solution { public: string minWindow(string S, string T) { int p1[256]={0}; //need to find int p2[256]={0}; //has found int count=0; int len1=S.size(); int len2=T.size(); for(int i=0;i<len2;i++) p1[T[i]]++; int start=0,end=0; int len=INT_MAX; //window大小 int pos=-1; for(;end<len1;end++) { if(p1[S[end]]==0) continue; //S[end]不在T中,跳过 p2[S[end]]++; if(p2[S[end]]<=p1[S[end]]) count++; if(count==len2) //找到一个window { while(p1[S[start]]==0||p2[S[start]]>p1[S[start]]) { if(p2[S[start]]>p1[S[start]]) p2[S[start]]--; start++; } if(len>end-start+1) { len=end-start+1; pos=start; } } } return (pos==-1)?"":S.substr(pos,len); } };
相关文章推荐
- LeetCode76 Minimum Window Substring(两种解法)
- [LeetCode] Minimum Window Substring
- Leetcode:Minimum Window Substring
- leetcode 76: Minimum Window Substring
- leetcode -- Minimum Window Substring -- 重点,应该会考
- Leetcode Minimum Window Substring
- LeetCode:Minimum Window Substring
- leetcode 67.Minimum Window Substring
- **LeetCode-Minimum Window Substring
- LeetCode76 Minimum Window Substring(两种解法)
- [Leetcode]Minimum Window Substring
- LeetCode刷题笔记(贪心):minimum-window-substring
- LeetCode 笔记系列16.3 Minimum Window Substring [从O(N*M), O(NlogM)到O(N),人生就是一场不停的战斗]
- [LeetCode] Minimum Window Substring
- Minimum Window Substring(leetcode)
- LeetCode Minimum Window Substring
- 【LeetCode】 Minimum Window Substring
- leetcode - Minimum Window Substring
- LeetCode 76 Minimum Window Substring (尺取法 推荐)
- LeetCode76 Minimum Window Substring(两种解法)