问题描述:
- 给定两个字符串
s
和p
,找到s
中所有p
的变位词的子串,返回这些子串的起始索引。- 字符串中只包含小写字母。
核心思路:
- 和剑指offer Ⅱ 014 的思路一样,滑动窗口 + 计数思想。
- 遇到符合条件的窗口就返回索引即可。
代码实现:
class Solution
{
public:
vector<int> findAnagrams(string s, string p)
{
int m = p.size(), n = s.size();
if(m > n) return {};
vector<int> a(26), b(26);
for(int i = 0; i < m; ++i)
++a[s[i]-'a'], ++b[p[i]-'a'];
vector<int> ans;
if(a == b) ans.push_back(0);
for(int i = m; i < n; ++i)
{
++a[s[i]-'a'];
--a[s[i-m]-'a'];
if(a == b) ans.push_back(i-m+1);
}
return ans;
}
};