438. Find All Anagrams in a String
Description:
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.
Difficulty:Easy
Example:
Input:
s: "cbaebabacd" p: "abc"
Output:
[0, 6]
方法: 滑动窗口
- Time complexity : O ( n ) O\left ( n \right ) O(n)
- Space complexity :
O
(
1
)
O\left ( 1 \right )
O(1)
思路:
先将p的元素出现次数计数到数组,再利用滑窗法,遍历s找相等
注意:滑窗数组的初始化,++和–的位置
class Solution {
public:
vector<int> findAnagrams(string s, string p) {
vector<int> sv(26, 0), pv(26, 0), res;
if (s.size() < p.size()) return res;
for (int i = 0; i < p.size(); i++){
sv[s[i] - 'a']++;
pv[p[i] - 'a']++;
}
if (sv == pv) res.push_back(0);
for (int i = p.size(); i < s.size(); i++) {
sv[s[i] - 'a']++;
sv[s[i - p.size()] - 'a']--;
if (sv == pv)
res.push_back(i-p.size()+1);
}
return res;
}
};