Skip to content

Commit 9d87e63

Browse files
committed
solve(w02): 242. Valid Anagram
1 parent 4333e4b commit 9d87e63

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

valid-anagram/seungriyou.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# https://leetcode.com/problems/valid-anagram/
2+
3+
class Solution:
4+
def isAnagram1(self, s: str, t: str) -> bool:
5+
"""
6+
[Complexity]
7+
- TC: O(nlogn)
8+
- SC: O(n)
9+
"""
10+
return sorted(s) == sorted(t)
11+
12+
def isAnagram2(self, s: str, t: str) -> bool:
13+
"""
14+
[Complexity]
15+
- TC: O(n)
16+
- SC: O(n)
17+
"""
18+
from collections import Counter
19+
20+
return Counter(s) == Counter(t)
21+
22+
def isAnagram(self, s: str, t: str) -> bool:
23+
"""
24+
[Complexity]
25+
- TC: O(n)
26+
- SC: O(n)
27+
"""
28+
from collections import defaultdict
29+
30+
cnt = defaultdict(int)
31+
32+
for _s in s:
33+
cnt[_s] += 1
34+
for _t in t:
35+
cnt[_t] -= 1
36+
37+
for k, v in cnt.items():
38+
if v != 0:
39+
return False
40+
41+
return True

0 commit comments

Comments
 (0)