LeetCode 567. 字符串的排列 (巧妙的滑动窗口)
作者:互联网
自己的麻瓜做法。。。
class Solution {
struct Freq{
int cnt[26] = {0};
bool ok(){
for(int i=0;i<26;i++){
if(cnt[i]!=0) return false;
}
return true;
}
void add(char c){
cnt[c-'a']++;
}
void remove(char c){
cnt[c-'a']--;
}
};
public:
Freq freq;
bool checkInclusion(string s1, string s2) {
int n1 = s1.size(), n2 = s2.size();
if(n1>n2) return false;
for(char c:s1){
freq.add(c);
}
for(int i=0;i<n1-1;i++){
freq.remove(s2[i]);
}
int r = n1-1, l = 0;
while(r<n2){
freq.remove(s2[r++]);
if(freq.ok()) return true;
freq.add(s2[l++]);
}
return false;
}
};
关键点:
- 滑动窗口长度加1,cnt数组的元素之和加1,
- cnt 数组元素始终维护为小于等于0,
- 当窗口长度为 n 的时候,正好所有元素都为0。
class Solution {
public:
bool checkInclusion(string s1, string s2) {
vector<int> cnt(26);
int n1 = s1.size(), n2 = s2.size();
if(n1 > n2) return false;
for(char c:s1) cnt[c-'a']--;
int l = 0, r = 0;
while(r < n2){
int x = s2[r++] - 'a';
cnt[x]++;
while(cnt[x]>0){
cnt[s2[l++]-'a']--;
}
if(r-l == n1) return true;
}
return false;
}
};
标签:cnt,return,int,s2,s1,567,滑动,freq,LeetCode 来源: https://blog.csdn.net/qq_44846324/article/details/113784267