-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy path0242. Valid Anagram.py
64 lines (54 loc) · 1.41 KB
/
0242. Valid Anagram.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
64
# Given two strings s and t , write a function to determine if t is an anagram of s.
#
# Example 1:
#
# Input: s = "anagram", t = "nagaram"
# Output: true
#
# Example 2:
#
# Input: s = "rat", t = "car"
# Output: false
#
# Note:
# You may assume the string contains only lowercase alphabets.
#
# Follow up:
# What if the inputs contain unicode characters? How would you adapt your solution to such case?
# 1) Sorting
# Time O(n log n)
# Space O(1). Space depends on the sorting implementation which, usually, costs O(1) auxiliary space if heapsort is used.
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return sorted(s) == sorted(t)
# 2) Hashmap
# Time O(n)
# Space O(n)
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
dic = {}
for c in s:
dic[c] = dic.get(c, 0) + 1
for c in t:
if c in dic and dic[c] > 0:
dic[c] -= 1
else:
return False
return True
# 3) Hashmap, similar to 2)
# Time O(n)
# Space O(n)
from collections import Counter
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
dic = Counter(s)
for c in t:
if c in dic and dic[c] > 0:
dic[c] -= 1
else:
return False
return True