438. Find All Anagrams in a String
I solved this problem using C++.
My idea: use unordered_map to store the count of characters in p, use lt and rt to represent the left and right pointers of the sliding window, and check if the current window is valid.
1 | class Solution |
e.g.
input: s = “ababababab” p = “aab”
output: [0, 2, 4, 6, 8]
- for
abin index01, key ins_countvalue is0 - now
ain index2, value ofs_countofais0, now window is valid because value for key inpis all0, result addlt - move
ltto right a step, movertto right a step, check if the window is valid… - find
bin index3, andbabin index123is not qualified withp, so find the current chbin previous str from left, and remove it and its left part str, now count from newlttort, and check if the window is valid.
e.g.
input: s = “cbaebabacd”, p = “abc”
output: [0, 6]
- for
cbain index012, key ins_countvalue is0and it is valid - not
ein index3, so resets_counttop_count, and movelttort + 1 babin index456, andbin index6is duplicated, so find the current chbin previous str from left, and remove it and its left part str, now count from newlttort, and check if the window is valid.- now
ltis5becausebin index4is removed, andrtis7, nowaandbis value0, need to findc…
use certain size sliding window
1 | class Solution |
maintain a sliding window of size p_len, and check if the current window is valid by comparing the count of characters in s and p. If they are equal, add the starting index of the window to the result.
conclusion
I think it is the same as the previous problem by using sliding window…😏😋