-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathanagrams.py
executable file
·63 lines (54 loc) · 1.58 KB
/
anagrams.py
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#!/usr/bin/python
# vim: foldlevel=0
"""
How to check if a string contains an anagram of another string?
Example: The string "coding interview questions" contains an anagram of the string
"weivretni".
http://blog.gainlo.co/index.php/2016/04/08/if-a-string-contains-an-anagram-of-another-string/
"""
from collections import defaultdict
def solution(a, b):
"""
>>> solution("coding interview questions", "weivretni")
True
>>> solution("coding interviw questions", "weivretni")
False
>>> solution("coding interview questions", "abcde")
False
"""
tracker = [0] * 256
for i in range(len(b)):
tracker[ord(b[i])] += 1
lo = 0
for hi in range(len(a)):
tracker[ord(a[hi])] -= 1
while hi-lo+1 > len(b):
tracker[ord(a[lo])] += 1
lo += 1
if hi-lo+1 == len(b) and all([c == 0 for c in tracker]):
return True
return False
def solution1(a, b):
"""
>>> solution1("coding interview questions", "weivretni")
True
>>> solution1("coding interviw questions", "weivretni")
False
>>> solution1("coding interview questions", "abcde")
False
"""
target_hash, rolling_hash = 0, 0
for i in range(len(b)):
target_hash += ord(b[i]) // 101
rolling_hash += ord(a[i]) // 101
i = 0
for j in range(len(b), len(a)):
if rolling_hash == target_hash:
return True
rolling_hash += ord(a[j]) // 101
rolling_hash -= ord(a[i]) // 101
i += 1
return False
if __name__ == "__main__":
import doctest
doctest.testmod()