Skip to content

Commit e54bbb5

Browse files
authored
Merge pull request #2412 from heesun-task/main
[heesun-task] WEEK 02 Solutions
2 parents 2a997a3 + af7b209 commit e54bbb5

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

valid-anagram/heesun-task.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# Leetcode 242. Valid Anagram
2+
class Solution:
3+
# Time Complexity: O(n)
4+
# Space Complexity: O(k)
5+
def isAnagram(self, s: str, t: str) -> bool:
6+
# base case:
7+
if len(s) != len(t):
8+
return False
9+
10+
# create a dictionary that counts the number of each letter in s
11+
s_dict = {}
12+
for s_letter in s:
13+
if s_letter in s_dict:
14+
s_dict[s_letter] += 1
15+
else:
16+
s_dict[s_letter] = 1
17+
18+
# loop the dictionary and match with the number of t
19+
for t_letter in t:
20+
if t_letter not in s_dict:
21+
return False
22+
else:
23+
s_dict[t_letter] -= 1
24+
if s_dict[t_letter] == 0:
25+
del s_dict[t_letter]
26+
27+
return len(s_dict) == 0

0 commit comments

Comments
 (0)