使用滑动窗口算法求解:
class Solution {
public:
vector<int> findAnagrams(string s, string p) {
vector<int> res;
unordered_map<char,int> need,window;
int left = 0,right = 0,match_cnt = 0;
//更新需要命中的全部字符
for(auto c:p) need[c] += 1;
while(right < s.size()){
char c = s[right];
right++;
if(need.count(c))
{
window[c] +=1 ;
if(window[c] == need[c])
match_cnt += 1;
}
while(right - left >= p.size())
{
if(match_cnt == need.size())
res.push_back(left);
char c = s[left];
left += 1;
if(need.count(c))
{
if(need[c] == window[c])
match_cnt -= 1;
window[c] -= 1;
}
}
}
return res;
}
};
运行效率:
Runtime: 20 ms, faster than 48.14% of C++ online submissions for Find All Anagrams in a String.
Memory Usage: 8.6 MB, less than 57.35% of C++ online submissions for Find All Anagrams in a String.