Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions valid-anagram/jylee2033.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
# If lengths differ, they cannot be anagrams
if len(s) != len(t):
return False

# Build a hashmap counting characters in t
char_count = {}

for letter in t:
if letter not in char_count:
char_count[letter] = 1
else:
char_count[letter] += 1
Comment on lines +10 to +14
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

파이썬 사전의 get() 함수를 활용하시면 코드가 좀 더 간결해질 것 같습니다.
(참고: https://daleseo.com/python-dictionary/)

Suggested change
for letter in t:
if letter not in char_count:
char_count[letter] = 1
else:
char_count[letter] += 1
for letter in t:
char_count[letter] = char_count.get(letter, 0) + 1


# Decrease counts using characters from s
for letter in s:
if letter not in char_count:
return False

char_count[letter] -= 1

# If count becomes negative, s has extra characters
if char_count[letter] < 0:
return False

return True
Loading