待补:
class Solution {
public:
string minWindow(string s, string t) {
int len = t.length();
for(int i = 0; len <= s.length(); ++i){
if(i + len <= s.length()){
string m(s,i,len);
if(subString(m,t)) return m;
}
else{
i=-1;
len++;
}
}
return "";
}
bool subString(string& s,string& t){/*
string::size_type position;
string a(s),b(t);
sort(a.begin(), a.end());
sort(b.begin(), b.end());
position = a.find(b);
if(position != string::npos) return true;
else return false;
}*/
bool subString(string& s,string& t){
int need[128]={0},needCnt = t.length();
for(char c: t){
need[c]++;
}
for(char c:s){
if(need[c]>0){
need[c]--;
needCnt--;
}
}
if(needCnt==0) return true;
else return false;
}
};
正解(滑动窗口):
class Solution {
public:
string minWindow(string s, string t) {
int l = 0, r = 0, needCnt = t.length(), size = INT_MAX;
int need[128]={0};
for(char c: t){
need[c]++;
}
int start = 0;
while(r < s.length()){
if(need[s[r]] > 0) needCnt--;
need[s[r]]--;
if(needCnt == 0){
while(l < r && need[s[l]]<0){
need[s[l++]]++;
}
if(r-l+1 < size){
size = r - l + 1;
start = l;
}
need[s[l++]]++;
needCnt++;
}
r++;
}
return size==INT_MAX ? "" : s.substr(start, size);
}
};
本文介绍了一种使用滑动窗口思想解决字符串处理问题的方法,具体为找到给定字符串中包含所有目标字符的最小子串。示例代码展示了如何在C++中实现这一算法,包括错误的初始实现和正确的解决方案。通过调整窗口大小,检查子串是否包含目标字符集,最终找到满足条件的最小子串。
1597

被折叠的 条评论
为什么被折叠?



