题意
题解
方法一:滑动窗口
维护一个定长的窗口,记录窗口内的状态
class Solution {
public:
vector<int> findAnagrams(string s, string p) {
vector<int> ans;
vector<int> count1(26);
vector<int> count2(26);
int s_length = s.size();
int p_length = p.size();
if (s_length < p_length) return {};
for (int i = 0; i < p_length; i++) {
count1[s[i]-'a']++;
count2[p[i]-'a']++;
}
if (count1 == count2) ans.push_back(0);
for(int i = p_length; i < s_length; i++) {
--count1[s[i-p_length]-'a'];
++count1[s[i]-'a'];
if (count1 == count2) ans.push_back(i-p_length+1);
}
return ans;
}
};
方法二:优化的滑动窗口
class Solution {
public:
vector<int> findAnagrams(string s, string p) {
vector<int> ans;
vector<int> count1(26);
int diff = 0;
int s_length = s.size();
int p_length = p.size();
if (s_length < p_length) return {};
for (int i = 0; i < p_length; i++) {
count1[s[i]-'a']++;
count1[p[i]-'a']--;
}
for (int i = 0; i < 26; i++) if (count1[i] != 0) diff++;
if (diff == 0) ans.push_back(0);
for (int i = p_length; i < s_length; i++) {
if (count1[s[i-p_length]-'a'] == 1) {
diff--;
} else if (count1[s[i-p_length]-'a'] == 0) {
diff++;
}
count1[s[i-p_length]-'a']--;
if (count1[s[i]-'a'] == -1) {
diff--;
} else if (count1[s[i]-'a'] == 0) {
diff++;
}
count1[s[i]-'a']++;
if (diff == 0) ans.push_back(i-p_length+1);
}
return ans;
}
};