Skip to content

Commit 9aa35f8

Browse files
committed
valid anagram solution
1 parent b00545f commit 9aa35f8

1 file changed

Lines changed: 27 additions & 0 deletions

File tree

valid-anagram/jylee2033.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
class Solution:
2+
def isAnagram(self, s: str, t: str) -> bool:
3+
# If lengths differ, they cannot be anagrams
4+
if len(s) != len(t):
5+
return False
6+
7+
# Build a hashmap counting characters in t
8+
char_count = {}
9+
10+
for letter in t:
11+
if letter not in char_count:
12+
char_count[letter] = 1
13+
else:
14+
char_count[letter] += 1
15+
16+
# Decrease counts using characters from s
17+
for letter in s:
18+
if letter not in char_count:
19+
return False
20+
21+
char_count[letter] -= 1
22+
23+
# If count becomes negative, s has extra characters
24+
if char_count[letter] < 0:
25+
return False
26+
27+
return True

0 commit comments

Comments
 (0)