Skip to content

Commit a544c4d

Browse files
committed
242. Valid Anagram Solution
1 parent 3d40dbc commit a544c4d

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

valid-anagram/doh6077.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# 1. First, check if s and t have the same length. If not, they are not anagrams, so return False.
2+
# 2. Create a dictionary to count how frequently each character appears in s.
3+
# 3. Loop through t and check if each character appears with the same frequency as in the dictionary.
4+
class Solution:
5+
def isAnagram(self, s: str, t: str) -> bool:
6+
if len(s) != len(t):
7+
return False
8+
9+
char_counts = {}
10+
for char_s in s:
11+
char_counts[char_s] = s.count(char_s)
12+
13+
for char_t in t:
14+
if char_t not in char_counts:
15+
# t has a character that s doesn't have
16+
return False
17+
else:
18+
count_in_t = t.count(char_t)
19+
if count_in_t != char_counts[char_t]:
20+
return False
21+
22+
return True

0 commit comments

Comments
 (0)