[leetcode]438. Find All Anagrams in a String
Analysis
everyday is the first day of your rest life—— [间歇性迷茫+1~]
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.
看s中是否包含p,输出子串在s中的起始位置。自己暴力做了一个一直超时,然后看了题解,用的滑动窗口,这题需要二刷!!!
Implement
class Solution {
public:
vector<int> findAnagrams(string s, string p) {
vector<int> res;
vector<int> cnt(128, 0);
int lens = s.length();
int lenp = p.length();
for(int i=0; i<lenp; i++)
cnt[p[i]]++;
int left = 0;
int right = 0;
int len = lenp;
while(right < lens){
if(cnt[s[right++]]-- >= 1){
len--;
}
if(len == 0)
res.push_back(left);
if(right-left == lenp && cnt[s[left++]]++ >= 0){
len++;
}
}
return res;
}
};