1+ 2+ 3+ # my solution
4+ def find_permutation2 (str1 , pattern ):
5+ start = 0
6+ char_map = {}
7+ result = []
8+ 9+ # add all characters in pattern to the hash map
10+ for s in pattern :
11+ char_map [s ] = char_map .get (s , 0 ) + 1
12+ 13+ for end in range (len (str1 )):
14+ right_char = str1 [end ]
15+ # for every character seen in str1 we decrement the count in the hash map
16+ char_map [right_char ] = char_map .get (right_char , 0 ) - 1
17+ if char_map [right_char ] == 0 :
18+ del char_map [right_char ]
19+ 20+ # slide the window when the number of characters in our sliding window has hit the length limit
21+ if end >= len (pattern ) - 1 :
22+ # if length of character map is zero then we have matched all the characters in the pattern
23+ if len (char_map ) == 0 :
24+ result .append (start )
25+ # begin to slide the window by taking note of the character exiting the window
26+ start_char = str1 [start ]
27+ char_map [start_char ] = char_map .get (start_char , 0 ) + 1 # add back the count to the char map when sliding out
28+ if char_map [start_char ] == 0 :
29+ del char_map [start_char ]
30+ start += 1 # slide the window ahead
31+ 32+ return len (result ) > 0
33+ 34+ def find_permutation (str1 , pattern ):
35+ window_start , matched = 0 , 0
36+ char_frequency = {}
37+ 38+ for chr in pattern :
39+ if chr not in char_frequency :
40+ char_frequency [chr ] = 0
41+ char_frequency [chr ] += 1
42+ 43+ # our goal is to match all the characters from the 'char_frequency' with the current window
44+ # try to extend the range [window_start, window_end]
45+ for window_end in range (len (str1 )):
46+ right_char = str1 [window_end ]
47+ if right_char in char_frequency :
48+ # decrement the frequency of matched character
49+ char_frequency [right_char ] -= 1
50+ if char_frequency [right_char ] == 0 :
51+ matched += 1
52+ 53+ if matched == len (char_frequency ):
54+ return True
55+ 56+ # shrink the window by one character
57+ if window_end >= len (pattern ) - 1 :
58+ left_char = str1 [window_start ]
59+ window_start += 1
60+ if left_char in char_frequency :
61+ if char_frequency [left_char ] == 0 :
62+ matched -= 1
63+ char_frequency [left_char ] += 1
64+ 65+ return False
66+ 67+ 68+ def main ():
69+ print ('Permutation exist: ' + str (find_permutation2 ("oidbcaf" , "abc" )))
70+ print ('Permutation exist: ' + str (find_permutation2 ("odicf" , "dc" )))
71+ print ('Permutation exist: ' + str (find_permutation2 ("bcdxabcdy" , "bcdyabcdx" )))
72+ print ('Permutation exist: ' + str (find_permutation2 ("aaacb" , "abc" )))
73+ 74+ print ('---' )
75+ 76+ print ('Permutation exist: ' + str (find_permutation ("oidbcaf" , "abc" )))
77+ print ('Permutation exist: ' + str (find_permutation ("odicf" , "dc" )))
78+ print ('Permutation exist: ' + str (find_permutation ("bcdxabcdy" , "bcdyabcdx" )))
79+ print ('Permutation exist: ' + str (find_permutation ("aaacb" , "abc" )))
80+ 81+ 82+ main ()
0 commit comments