-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanagram.py
More file actions
28 lines (19 loc) · 701 Bytes
/
anagram.py
File metadata and controls
28 lines (19 loc) · 701 Bytes
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
def isAnagram(s: str, t: str) -> bool:
# If lengths are different, they can't be anagrams
if len(s) != len(t):
return False
return sorted(s) == sorted(t)
print(isAnagram('anagram','anagram'))
# this is better option.
'''Why this matters
Sorting takes $O(n \log n)$ time.
Hash Map takes $O(n)$ time because we only go through the strings once.'''
def isAnagramBetterSol(s: str, t: str) -> bool:
if len(s) != len(t):
return False
countS, countT = {}, {}
for i in range(len(s)):
countS[s[i]] = 1 + countS.get(s[i], 0)
countT[t[i]] = 1 + countT.get(t[i], 0)
return countS == countT
print(isAnagramBetterSol('anagram','anagram'))