Leetcode 438. 找到字符串中所有字母异位词
思路:维护长度为p的滑动窗口
使用 h a s h hash hash存每个字符出现的次数,每一次加入一个字符判断加入的字符是否构成符合条件的字符,如果符合条件的字符数量跟 p p p字符串中字符串数量相同,就找到了一个满足要求的单词
时间复杂度: O ( n ) O(n) O(n), s s s字符串长度
空间复杂度: O ( C ) O(C) O(C), p p p字符串出现的不同字母个数,最大为26
class Solution {
public:
vector<int> findAnagrams(string s, string p) {
unordered_map<char, int> cnt;
for (auto& c : p) cnt[c] ++ ;
int tot = cnt.size();
vector<int> res;
for (int i = 0, j = 0, f = 0; i < s.size(); i ++ ) {
if (-- cnt[s[i]] == 0) f ++ ;
if (i - j + 1 > p.size()) {
if (cnt[s[j]] == 0) f -- ;
cnt[s[j ++ ]] ++ ;
}
if (f == tot) res.push_back(j);
}
return res;
}
};