1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| class Solution { public: vector<int> findAnagrams(string s, string p) { vector<int> res; if(s.size() < p.size()) return res;
vector<int> cnt(26,0);
for(char c: p){ cnt[c - 'a']++; }
int left = 0, right = 0; int need = p.size();
while(right < s.size()){ if(cnt[s[right] - 'a'] > 0){ need--; } cnt[s[right] - 'a']--; right++;
if(right - left == p.size()){ if(need == 0){ res.push_back(left); }
if(cnt[s[left] - 'a'] >= 0){ need++; } cnt[s[left] - 'a']++; left++; } } return res; } };
|