问题:https://leetcode.com/problems/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.
分析:先用一个数组统计p中元素出现的次数,再遍历s,从第一个值开始每次找p中元素长度,看是否是p中的乱序,来验证字符个数是否相同,如果不相同出现了直接break,如果是就记录下此时是从s中哪个位置开始的。
代码:
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;
}
};