76. Minimum Window Substring
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).
Example:
Input: S = "ADOBECODEBANC", T = "ABC"
Output: "BANC"
Note:
- If there is no such window in S that covers all characters in T, return the empty string
""
. - If there is such window, you are guaranteed that there will always be only one unique minimum window in S.
题目链接:https://leetcode.com/problems/minimum-window-substring/
解法:滑动窗口
数组储存
class Solution {
public:
string minWindow(string s, string t) {
int lens = s.length(), lent = t.length();
int minw = INT_MAX, minl = -1;
if(lens<lent) return "";
int charlist[128]={0}, tmp[128]={0};
for(int i=0; i<lent;++i){
charlist[int(t[i])]++;
tmp[int(s[i])]++;
}
int l=0, r=lent-1;
while(true){
if(hasStr(tmp, charlist)){
if(r-l+1<minw){
minw = r-l+1;
minl=l;
}
tmp[int(s[l])]--;
l++;
}else if(r+1<lens){
r++;
tmp[int(s[r])]++;
}else break;
}
if(minl==-1) return "";
else return s.substr(minl, minw);
}
bool hasStr(int a[], int b[]){
int len = 128;
for(int i=0;i<len;++i){
if(b[i]>0 && a[i]<b[i]) return false;
}
return true;
}
};
优化:判断是否满足的方法
前一种方法判断是否满足,是使用了判断整个数组里要求的内容是否相等,可以优化为使用count来计数当前还有几个目标元素没有满足。
class Solution {
public:
string minWindow(string s, string t) {
int lens = s.length(), lent = t.length();
int minw = INT_MAX, minl = -1;
if(lens<lent) return "";
int charlist[128]={0}, count=lent;
for(int i=0; i<lent;++i){
charlist[int(t[i])]++; // 记录给个ascii码对应的元素需要几个
}
int l=0, r=0;
while(r<lens){
charlist[int(s[r])]--;
if(charlist[int(s[r])]>=0){
count--; // >=0说明当前r取到的元素在目标之中
}
while(count==0){
if(r-l+1<minw){
minw=r-l+1;
minl=l;
}
charlist[int(s[l])]++;
if(charlist[int(s[l])]>0) count++; // >0说明该ascii码对应元素有缺
l++;
}
r++;
}
if(minl==-1) return "";
else return s.substr(minl, minw);
}
};