438. Find All Anagrams in a String

Given a string s and a non-empty string p, find all the start indices of p’s anagrams in s.

Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.

The order of output does not matter.

Example 1:

``````Input:
s: "cbaebabacd" p: "abc"

Output:
[0, 6]

Explanation:
The substring with start index = 0 is "cba", which is an anagram of "abc".
The substring with start index = 6 is "bac", which is an anagram of "abc".
``````

Example 2:

``````Input:
s: "abab" p: "ab"

Output:
[0, 1, 2]

Explanation:
The substring with start index = 0 is "ab", which is an anagram of "ab".
The substring with start index = 1 is "ba", which is an anagram of "ab".
The substring with start index = 2 is "ab", which is an anagram of "ab".
``````

``````class Solution {
public:
vector<int> findAnagrams(string s, string p) {
if (s.empty()) return {};
vector<int> res, cnt(128, 0);
int ns = s.size(), np = p.size(), i = 0;
for (char c : p) ++cnt[c];
while (i < ns) {
bool success = true;
vector<int> tmp = cnt;
for (int j = i; j < i + np; ++j) {
if (--tmp[s[j]] < 0) {
success = false;
break;
}
}
if (success) {
res.push_back(i);
}
++i;
}
return res;
}
};
``````

``````class Solution {
public:
vector<int> findAnagrams(string s, string p) {
if (s.empty()) return {};
vector<int> res, m1(256, 0), m2(256, 0);
for (int i = 0; i < p.size(); ++i) {
++m1[s[i]]; ++m2[p[i]];
}
if (m1 == m2) res.push_back(0);
for (int i = p.size(); i < s.size(); ++i) {
++m1[s[i]];
--m1[s[i - p.size()]];
if (m1 == m2) res.push_back(i - p.size() + 1);
}
return res;
}
};
``````

``````class Solution {
public:
vector<int> findAnagrams(string s, string p) {
if (s.empty()) return {};
vector<int> res, m(256, 0);
int left = 0, right = 0, cnt = p.size(), n = s.size();
for (char c : p) ++m[c];
while (right < n) {
if (m[s[right++]]-- >= 1) --cnt;
if (cnt == 0) res.push_back(left);
if (right - left == p.size() && m[s[left++]]++ >= 0) ++cnt;
}
return res;
}
};
``````

Github 同步地址：

https://github.com/grandyang/leetcode/issues/438

Valid Anagram

Anagrams

https://leetcode.com/problems/find-all-anagrams-in-a-string/

https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/92015/ShortestConcise-JAVA-O(n)-Sliding-Window-Solution

https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/92027/c-on-sliding-window-concise-solution-with-explanation

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation