[LeetCode] Find All Anagrams in a String

438. Find All Anagrams in a String

Given two strings s and p, return an array of all the start indices of p’s anagrams in s. You may return the answer in any order.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
vector<int> findAnagrams(string s, string p) {
if(p.size() > s.size()) return {};
vector<int> sArr(26), pArr(26);
vector<int> res;
for(int i = 0; i < p.size(); i++) {
sArr[s[i] - 'a']++;
pArr[p[i] - 'a']++;
}
for(int i = 0; i < s.size()-p.size(); i++) {
if(sArr == pArr) res.push_back(i);
sArr[s[i + p.size()] - 'a']++;
sArr[s[i] - 'a']--;
}
if(sArr == pArr) res.push_back(s.size() - p.size());

return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/02/PS/LeetCode/find-all-anagrams-in-a-string/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.