Description:
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.
Code:
struct record{ int start, end, length; record(){ start=end=length = 0; }};class Solution {public: bool isWindowContainT(int * win, int * ch_t) { for (int i = 0; i < 256; ++i) { if (win[i] < ch_t[i]) return false; } return true; } string minWindow(string s, string t) { unsigned int lengthS = s.size(); unsigned int lengthT = t.size(); if (lengthT > lengthS) return ""; int ch_t[256], ch_win[256]; for (int i = 0; i < 256; ++i) { ch_t[i] = 0; ch_win[i] = 0; } for (int i = 0; i < lengthT; ++i) ch_t[t[i]]++; int start = 0, end = 0; ch_win[s[0]]=1; record min; min.length = INT_MAX; bool flag = false; while (end < lengthS) { if ( isWindowContainT(ch_win, ch_t) ) { flag = true; if (end-start+1 < min.length) { min.start = start; min.end = end; min.length = end-start+1; } ch_win[s[start]]--; start++; } else { ch_win[s[++end]]++; } } if (flag) return s.substr(min.start, min.end-min.start+1); else return ""; }};
注意:T中允许字符重复
思路:双指针,动态维护一个区间。尾指针不断往后扫,当扫到有一个窗口包含了所有T的字符后,然后再收缩头指针,直到不能再收缩为止。最后记录所有可能的情况中窗口最小的