iven 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 sand 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]
分析:
给定两个字符串s和p,找出s中所有包含p的异位词的位置,字母异位词是指包含的字母相同但顺序不同。首先统计p中每个字符出现的次数,然后从s的开头开始,每次找p.size()个字符,来验证字符个数是否相同,如果不相同直接break,如果一直都相同,则将起始位置加入结果res中。
class Solution {
public:
vector<int> findAnagrams(string s, string p) {
if (s.empty())
return {};
int len1 = s.size();
int len2 = p.size();
vector<int> res;
vector<int> tmp1(128 , 0);
int i = 0;
for(char c : p)
tmp1[c]++;
while(i < len1)
{
bool flag = true;
vector<int> tmp2 = tmp1;
for(int j = i; j < i + len2; j++)
{
if(--tmp2[s[j]] < 0)
{
flag = false;
break;
}
}
if(flag)
res.push_back(i);
i++;
}
return res;
}
};