https://leetcode.com/problems/find-all-anagrams-in-a-string/description/
vector<int> findAnagrams(string s, string p) {
if(s.size()<p.size()) return {};
int np = p.size();
vector<int> stat('z'+1, 0), res;
for(int i=0; i<np; i++) {
stat[s[i]]++;
stat[p[i]]--;
}
stat[s[np-1]]--;
for(int i=np-1; i<s.size(); i++) {
stat[s[i]]++;
int j = 0;
for(j='a'; j<'z'+1; j++) {
if(stat[j]!=0) break;
}
if(j=='z'+1) res.push_back(i-np+1);
stat[s[i-np+1]]--;
}
return res;
}
No comments:
Post a Comment