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
| class Solution { public: vector<int> findAnagrams(string s, string p) { unordered_map<char, int> map; for(auto ch : p) ++map[ch]; int count = map.size(); vector<int> ret; int begin = 0, end = 0, n = s.size(), m = p.size(); while(end < n) { if(map.count(s[end]) && --map[s[end]] == 0) --count; while(count == 0) { if(end - begin + 1 == m) ret.push_back(begin); if(map.count(s[begin]) && ++map[s[begin]] > 0) ++count; ++begin; } ++end; } return ret;
} };
|