[코테] 242. Valid Anagram
My Solution
1
2
3
4
5
6
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
return sorted(s) == sorted(t)
Other Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
# 1. 길이가 다르면 즉시 False (가장 빠른 탈출)
if len(s) != len(t):
return False
count = {} # 해시 테이블 (딕셔너리) 생성
# 2. s 문자열의 문자 개수를 셉니다.
for char in s:
# get(char, 0)은 char가 없으면 0을 반환
count[char] = count.get(char, 0) + 1
# 3. t 문자열을 순회하며 개수를 뺍니다.
for char in t:
# 만약 t의 문자가 count에 없으면 (s에는 없는 문자)
if char not in count:
return False
# 만약 t의 문자가 s보다 많으면 (count가 0이 됨)
if count[char] == 0:
return False
# 개수를 1 뺍니다.
count[char] -= 1
# 4. 모든 검사를 통과했으면 True
return True
This post is licensed under CC BY 4.0 by the author.