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
ab
in index01
, key ins_count
value is0
- now
a
in index2
, value ofs_count
ofa
is0
, now window is valid because value for key inp
is all0
, result addlt
- move
lt
to right a step, movert
to right a step, check if the window is valid… - find
b
in index3
, andbab
in index123
is not qualified withp
, so find the current chb
in previous str from left, and remove it and its left part str, now count from newlt
tort
, and check if the window is valid.
e.g.
input: s = “cbaebabacd”, p = “abc”
output: [0, 6]
- for
cba
in index012
, key ins_count
value is0
and it is valid - not
e
in index3
, so resets_count
top_count
, and movelt
tort + 1
bab
in index456
, andb
in index6
is duplicated, so find the current chb
in previous str from left, and remove it and its left part str, now count from newlt
tort
, and check if the window is valid.- now
lt
is5
becauseb
in index4
is removed, andrt
is7
, nowa
andb
is 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…😏😋