Minimum Window Substring -- LeetCode
2015-04-01 08:31
453 查看
题目:
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.
思路:使用两个指针,一个hash表,两个指针为了记录宽度,hash表为了记录是否存在,目标字符在两个指针之间出现了多少次,直到所有字符都出现在了这段子串内,移动前面的指针,直到某一个字符出现在子串中一次,那么这个空间的长度就是当前最短的,这样遍历直到把所有字符串遍历结束
#include <iostream> #include <vector> #include <string> using namespace std; /* 一个字符串能包含另一个字符串中所有字母的子串的最小长度 */ string MinLength(string& src,string& dest) { int i=0,j=0; int flag =0; int len=src.size(); int pos=0; vector<int> hash(26,-1); for(i=0;i<dest.length();i++) hash[dest[i]-'A'] =0; // for(i=0;i<hash.size();i++) // cout<<hash[i]<<endl; for(i=0;i<src.size();i++) { if(hash[src[i]-'A'] >=0) { hash[src[i]-'A']++; if(hash[src[i]-'A'] ==1) flag++; } if(flag == dest.length()) { //cout<<"=="<<endl; // cout<<"j is "<<j<<" i is "<<i<<endl; for(;j<i;j++) { if(hash[src[j]-'A'] == 1) break; else hash[src[j]-'A']--; } if(len >i-j+1) { len = i-j+1; pos =j; } hash[src[j]-'A'] = 0; j++; flag--; } } cout<<string(src,pos,pos+len)<<" pos is "<<pos<<" len is "<<len<<endl;; return string(src,pos,pos+len); } int main() { string src("ADOBECODEBANCAAABC"); string dest("ABC"); cout<<MinLength(src,dest); return 0; }
相关文章推荐
- Minimum Window Substring 最小子串窗口@LeetCode
- LeetCode 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 Minimum Window Substring
- [LeetCode] Minimum Window Substring
- LeetCode76 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 76 Minimum Window Substring
- LeetCode Minimum Window Substring