[LeetCode] Minimum Window Substring
2014-12-12 16:00
405 查看
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(1)的速度来获取某个字符的出现次数,必须以空间换取时间,我的想法有两个,一个是使用数组记录,另外一个就是使用HashMap来保存,当然,暂时使用的是数组,同时,再扫描数据的过程中统计有效次数有多少,依次有效的字符是出现再目标子字符中的,并且从当前开始字符到目前为止出现次数不大于目标字符串中该字符的出现次数。当有效次数达到了目标字符的总数之后,再从开始的字符开始扫描一遍以便获取开始的位置。再次过程中我们还要对现有的统计必要的更改。
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(1)的速度来获取某个字符的出现次数,必须以空间换取时间,我的想法有两个,一个是使用数组记录,另外一个就是使用HashMap来保存,当然,暂时使用的是数组,同时,再扫描数据的过程中统计有效次数有多少,依次有效的字符是出现再目标子字符中的,并且从当前开始字符到目前为止出现次数不大于目标字符串中该字符的出现次数。当有效次数达到了目标字符的总数之后,再从开始的字符开始扫描一遍以便获取开始的位置。再次过程中我们还要对现有的统计必要的更改。
class MinWindow { private: static const int CHARCOUNT = 256; int countN[CHARCOUNT],countT[CHARCOUNT]; int usefulCount; public: string minWindow(string S, string T) { usefulCount = 0; memset(countN,0, sizeof(countN)); memset(countT,0, sizeof(countT)); for(int i=0;i<T.length();i++) { countT[T[i]-'A']++; } int retBegin = -1 ,retEnd = -1; int minLength = INT_MAX; int begin = 0,i=0; for(i=0;i<S.length();i++) { char c = S[i]; if(countT[c-'A']==0) continue; if(countN[c-'A']<countT[c-'A']) { countN[c-'A']++; usefulCount++; } else countN[c-'A']++; if(usefulCount==T.length()) { for(int k=begin;k<= i;k++) { char ic = S[k]; if(countT[ic-'A']==0) continue; if(countN[ic-'A']>countT[ic-'A']) countN[ic-'A']--; else if(countN[ic-'A']==countT[ic-'A']) { countN[ic-'A']--; usefulCount--; begin = k; break; } } if(i-begin<minLength) { retBegin = begin; retEnd = i; minLength = i-begin; } begin++; } } return retBegin == -1?"":S.substr(retBegin,retEnd-retBegin+1); } };
相关文章推荐
- LeetCode – Refresh – Minimum Window Substring
- LeetCode 76 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
- Minimum Window Substring 最小子串窗口@LeetCode
- LeetCode-Minimum Window Substring -- 窗口问题
- LeetCode: Minimum Window Substring
- leetcode——Minimum Window Substring
- LeetCode: 76. Minimum Window Substring
- Leetcode231: Minimum Window Substring
- [Leetcode] minimum window substring 最小字符窗口
- LeetCode76 Minimum Window Substring(两种解法)
- leetcode76题 Minimum Window Substring
- leetcode解题笔记-Minimum Window Substring
- 【LeetCode】Minimum Window Substring