🔤 [Python] 아나그램(Anagram) 판별하기 – dict.get() vs collections.Counter
문제 (Problem):
Given two strings s and t, return True if t is an anagram of s, and False otherwise.
조건:
- 문자열 길이: 1 <= s.length, t.length <= 5 * 10⁴
- 문자열은 소문자 영문으로만 구성
- ⚠️ Follow-up: If Unicode characters are allowed?
🧠 아나그램(Anagram)이란?
두 문자열이 같은 문자로 구성되어 있으며, 각 문자의 개수도 동일한 경우.
예:
s = "anagram"
t = "nagaram"
→ True
s = "rat"
t = "car"
→ False
✅ 방법 1:
collections.Counter
사용 (가장 쉽고 깔끔)
from collections import Counter
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return Counter(s) == Counter(t)
🔍 설명:
- Counter(s)는 각 문자의 등장 횟수를 딕셔너리처럼 반환
- 예: Counter("abbc") → {'a': 1, 'b': 2, 'c': 1}
- 두 Counter 객체를 비교해 동일한지 확인
⏱ 시간 복잡도:
- Time: O(n)
- Space: O(1) (영문자는 최대 26개)
✅ 방법 2:
dict.get()
으로 직접 구현
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
count = {}
for c in s:
count[c] = count.get(c, 0) + 1
for c in t:
if c not in count or count[c] == 0:
return False
count[c] -= 1
return True
🔍 설명:
- count.get(c, 0) → 키가 없으면 기본값 0으로 시작
- s의 각 문자 수를 저장한 뒤,
- t를 순회하며 count 값을 차감
- 만약 값이 0보다 작아지거나 없는 문자가 있으면 False
🤔 두 방식 비교 (Counter vs dict.get)
항목Counter 방식dict.get 방식
| 코드 길이 | ✅ 짧고 직관적 | 조금 더 길고 명시적 |
| 성능 | O(n) | O(n) |
| 이해 난이도 | 쉬움 | 중간 (get 메서드 이해 필요) |
| Unicode 처리 | ✅ 기본 지원 | 수동 정규화 필요 |
| 실무 활용도 | 높음 | 낮음 (직접 구현이므로 실전보다는 연습용) |
🧪 확장 질문: Unicode 문자는?
🤖
Counter
는 Unicode도 처리 가능:
Counter("漢字abc漢") → {'漢': 2, '字': 1, 'a': 1, 'b': 1, 'c': 1}
🛠 단, Unicode 정규화가 필요한 경우엔 다음을 써야 함:
import unicodedata
s = unicodedata.normalize("NFC", s)
t = unicodedata.normalize("NFC", t)
📌 정리 (Summary)
조건추천 방식
| 빠르게 정확하게 풀기 | ✅ collections.Counter |
| dict 기본기 연습용 | dict.get() |
| Unicode 포함 가능성 있음 | Counter + unicodedata.normalize() |
🔗 마무리 (Closing Thoughts)
이 문제는 문자열 처리의 기본기인 문자 등장 횟수 비교를 연습하기에 매우 좋은 문제다
초보자라면 sorted() 방식으로 접근해도 좋고,
중급자라면 Counter와 dict를 모두 구현해보며 로직을 비교하는 것을 추천
'Coding Test' 카테고리의 다른 글
| 6. Top K Frequent Elements (0) | 2025.06.13 |
|---|---|
| 5. Group Anagrams (0) | 2025.06.12 |
| 2. Best Time to Buy and Sell Stock (0) | 2025.06.11 |
| 1. Two Sum (1) | 2025.06.09 |
| 피라미드 만들기 (0) | 2023.04.13 |