力扣438. 找到字符串中所有字母异位词(滑动窗口)

常规的滑动窗口问题,要注意满足答案的条件:1.窗口长度与p字符串长度一致2.字符充足的个数与p中不重复个数相同
1 class Solution { 2 public: 3 vector<int> findAnagrams(string s, string p) { 4 vector<int> res; 5 unordered_map<char, int> window, need; 6 for (auto i : p) { 7 need[i]++; 8 } 9 int left = 0, right = 0; 10 int enough = 0; //记录窗口中字符数量充足的个数,注意:字符充足并不完全符合题意,需要字符数量完全一致才行 11 while (right < s.length()) { 12 if (need.count(s[right])) { 13 window[s[right]]++; 14 if (window[s[right]] == need[s[right]]) { 15 enough++; 16 } 17 } 18 right++; 19 while (enough == need.size()) { 20 if (need.count(s[left])) { 21 if (right - left == p.size()) { //窗口长度等于p的长度 22 res.push_back(left); 23 } 24 if (window[s[left]] == need[s[left]]) { 25 enough--; 26 } 27 window[s[left]]--; 28 } 29 left++; 30 } 31 } 32 return res; 33 } 34 };
浙公网安备 33010602011771号