Description Link to heading
438.find-all-anagrams-in-a-string
Solution Link to heading
Similar to 30.substring-with-concatenation-of-all-words, easier.
Code Link to heading
class Solution {
public:
vector<int> findAnagrams(string s, string p) {
unordered_map<char, int> mp;
for (char &c : p)
mp[c]++;
vector<int> res;
unordered_map<char, int> tmp = mp;
for (int l = 0, r = 0; r < s.size(); r++) {
if (tmp.find(s[r]) != tmp.end()) {
tmp[s[r]]--;
if (tmp[s[r]] == 0) {
tmp.erase(s[r]);
if (tmp.empty()) {
res.push_back(l);
tmp[s[l++]]++;
}
}
} else {
if (mp.find(s[r]) != mp.end()) {
while (s[l] != s[r]) {
tmp[s[l]]++;
l++;
}
l++;
} else { //s[r]不在p中
l = r + 1;
tmp = mp;
}
// l++;
}
}
return res;
}
};