vector<int> findAnagrams(string s, string p) { vector<int> pMap(26, 0); for (char ch : p) { ++pMap[ch - 'a']; } int left = 0; int right = 0; int count = (int)p.length(); vector<int> ans; while (right < s.length()) { //move right everytime, if the character exists in p's hash, decrease the count //current hash value >= 1 means the character is existing in p if (pMap[s[right++] - 'a']-- >= 1) { --count; }
//when the count is down to 0, means we found the right anagram //then add window's left to result list if (count == 0) { ans.push_back(left); } //if we find the window's size equals to p, then we have to move left (narrow the window) to find the new match window //++ to reset the hash because we kicked out the left //only increase the count if the character is in p //the count >= 0 indicate it was original in the hash, cuz it won't go below 0 if (right - left == p.length() && pMap[s[left++] - 'a']++ >= 0) { ++count; } } return ans; }