当t不是字串时的模板
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<vector>
#include<algorithm>
using namespace std;
typedef long long LL;
const int N=1e5+10;
int arr[N];
int main()
{
int T;
cin>>T;
while(T--)
{
int n,s;
cin>>n>>s;
for(int i=0; i<n; i++)cin>>arr[i];
int res=n+1,sum=0;
for(int l=0,r=0; r<n; r++)
{
sum+=arr[r];
if(sum<s)continue;
while(sum-arr[l]>=s)sum-=arr[l++];
res=min(res,r-l+1);
}
if(res==n+1)cout<<0<<endl;
else cout<<res<<endl;
}
return 0;
}
scnaf的重要性
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<vector>
#include<algorithm>
#include<set>
#include<map>
using namespace std;
typedef long long LL;
const int N=1e6+10;
int a[N];
int main()
{
int p;
cin>>p;
set<int> com;
map<int,int> mp;
com.clear(); /*初始化*/
mp.clear();
for(int i=1; i<=p; i++)
{
//cin>>a[i];
scanf("%d",&a[i]);
com.insert(a[i]);
}
int total=com.size(),sum=0;
int ans=p,r=1,l=1;
while(r<=p)
{
if(mp[a[r]]==0)sum++;
mp[a[r]]++;
while(mp[a[l]]>1)
{
mp[a[l]]--;
l++;
}
if(sum<total)
{
r++;
continue;
}
// res=min(res,r-l+1);
// if(m[arr[l]]==1)nums--;
// m[arr[l]]--;
// l++;
// }
if(total==sum)
{
ans=min(ans,r-l+1);
if(mp[a[l]]==1)sum--;
mp[a[l]]--;
l++;
}
r++;
}
cout<<ans<<endl;
return 0;
}
class Solution
{
public:
string minWindow(string s, string t)
{
string res="";
int n=s.size();
if(!n)return res;
unordered_map<char,int>need,window;
int left=0,right=0,valid=0,len=n,start=0;
for(char c:t)need[c]++;
while(right<n)
{
char c=s[right];
right++;
if(need.count(c))
{
window[c]++;
if(need[c]==window[c])valid++;
}
while(valid==need.size())//T不是S的字串时使用这样
{
if(right-left<len)
{
len=right-left;
start=left;
}
char r=s[left];
left++;
if(need.count(r))
{
if(need[r]==window[r])valid--;
window[r]--;
}
}
}
return s.substr(start,len);
}
};
当t是字串或者字串的排列时的模板
// 判断 s 中是否存在 t 的排列
bool checkInclusion(string t, string s) {
unordered_map<char, int> need, window;
for (char c : t) need[c]++;
int left = 0, right = 0;
int valid = 0;
while (right < s.size()) {
char c = s[right];
right++;
// 进行窗口内数据的一系列更新
if (need.count(c)) {
window[c]++;
if (window[c] == need[c])
valid++;
}
// 判断左侧窗口是否要收缩
while (right - left >= t.size()) {因为是字串,所以长度要与T相同
// 在这里判断是否找到了合法的子串
if (valid == need.size())
return true;
char d = s[left];
left++;
// 进行窗口内数据的一系列更新
if (need.count(d)) {
if (window[d] == need[d])
valid--;
window[d]--;
}
}
}
// 未找到符合条件的子串
return false;
}
作者:labuladong
链接:https://leetcode-cn.com/problems/minimum-window-substring/solution/hua-dong-chuang-kou-suan-fa-tong-yong-si-xiang-by-/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。