Problem:438. 找到字符串中所有字母异位词
思路:哈希记录,定长滑动窗口搜索
相似题:
字符串排列
Accode:
class Solution {
public:
vector<int> findAnagrams(string s, string p) {
int len = s.length(), k = p.length();
vector<int> cnt(26,0),cnt_p(26,0);
deque<int> deq;
vector<int> ans;
for(auto item:p){
cnt_p[item-'a']++;
}
for(int i=0;i<len;i++){
if(deq.size() && i-deq.front()+1>k){
int idx = s[deq.front()]-'a';
cnt[idx]--;
deq.pop_front();
}
deq.push_back(i);
cnt[s[i]-'a']++;
if(i+1>=k){
bool flag = true;
for(int i=0;i<26;i++){
if(cnt[i]!=cnt_p[i]){
flag = false;
break;
}
}
if(flag) ans.push_back(deq.front());
}
}
return ans;
}
};
时间复杂度:$o(26*n)$