Find All Anagrams in a String
https://leetcode.com/problems/find-all-anagrams-in-a-string/description/
Thoughts
Code
/*
* @lc app=leetcode id=438 lang=cpp
*
* [438] Find All Anagrams in a String
*/
// @lc code=start
class Solution {
public:
vector<int> findAnagrams(string s, string p) {
vector<int> res;
if (s.length() < p.length()) return res;
vector<int> freq(26, 0);
int l = 0, r = 0, cnt = 0, N = p.length();
for (const auto c : p) --freq[c - 'a'];
for (; r < N; ++r) {
const auto k = s[r] - 'a';
if (freq[k] < 0) ++cnt;
++freq[k];
}
if (cnt == N) res.push_back(l);
while (r < s.length()) {
const auto k = s[r] - 'a', l = s[r - N] - 'a';
if (freq[k] < 0) ++cnt;
++freq[k];
if (freq[l] <= 0) --cnt;
--freq[l];
if (cnt == N) res.push_back(r - N + 1);
++r;
}
return res;
}
};
// @lc code=end
Analysis
Last updated