题意:
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.
思路:
双指针
代码:
class Solution {
public:
vector<int> findAnagrams(string s, string p) {
vector<int> cnt(27,0);
for (char ch : p)
cnt[ch - 'a']++;
vector<int> ret;
int start = 0;
s+= '{'; // 哨兵
/*
* 若不添加哨兵,代码量会稍微大些,比较麻烦
* 考虑不添加哨兵,若s[i, s.size() - 1]满足条件时,下面for循环会溜掉这种情况。
*/
for (int i = 0; i < s.size(); ++i)
if (--cnt[s[i] - 'a'] < 0){
if (i - start == p.size())
ret.push_back(start);
while(cnt[s[i] - 'a'] < 0 && start < s.size())
++cnt[s[start++] -'a'];
}
return ret;
}
};