| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 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 | 28 |
Tags
- C++
- 파이썬
- 해커랭크
- ProblemSolving
- Algorithm
- 프로그래머스
- LEVEL 2
- 알고리즘
- Code Jam 2022
- Code Jam
- 문제해결
- First Unique Character in a String
- 2022
- 코딩테스트
- Python
- leetcode
- 하늘과 바람과 별과 詩
- swift
- Certbot/dns-route53
- MySQL
- Count Monobit Integers
- 리트코드
- Qualification Round
- GitLab
- Kubernetes
- hackerrank
- 3D PRINTING
- 하늘과 바람과 별과 시
- K8S
Archives
- Today
- Total
공대생의 비망록
[LeetCode][Easy] Valid Anagram 문제 Python 풀이 본문
Programming Language/Python
[LeetCode][Easy] Valid Anagram 문제 Python 풀이
myungsup1250 2026. 2. 8. 18:49주어진 두 문자열 s, t가 애너그램 (Anagram)인 지 판단하는 문제.
문제에서는 문자열 안에는 소문자만 포함된다고 하였으나 확장성을 고려하여 딕셔너리 (dictionary) 자료구조를 활용하여 푼 버전과 소문자 26개 (혹은 존재하는 소문자 수)만큼의 길이를 가지는 배열 (list)을 활용하여 푼 버전을 각각 구현해보았다:
딕셔너리 활용 버전:
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
dicts = {}; dictt = {}
for ch in s:
if ch not in dicts:
dicts[ch] = 1
else:
dicts[ch] += 1
for ch in t:
if ch not in dictt:
dictt[ch] = 1
else:
dictt[ch] += 1
for key in dicts.keys():
if key not in dictt or dicts[key] != dictt[key]:
return False
return True
문자열 활용 버전:
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
sets = set(s); sett = set(t)
if len(sets - sett) != 0 or len(sett - sets) != 0:
return False
mydict = {}; i = 0
for ch in sets:
mydict[ch] = i
i += 1
chars = [0 for _ in range(len(s))]
for j in range(len(s)):
sindex = mydict[s[j]]
chars[sindex] += 1
tindex = mydict[t[j]]
chars[tindex] -= 1
for num in chars:
if num != 0:
return False
return True'Programming Language > Python' 카테고리의 다른 글
| [LeetCode][Easy] Valid Palindrome 문제 Python 풀이 (0) | 2026.02.09 |
|---|---|
| [LeetCode][Easy] First Unique Character in a String 문제 Python 풀이 (0) | 2026.02.09 |
| [LeetCode][Easy] Count Monobit Integers 문제 Python 풀이 (0) | 2026.02.08 |
| [LeetCode][Easy] Single Number 문제 Python 풀이 (0) | 2026.02.08 |
| [LeetCode][Easy] Missing Number 문제 Python 풀이 (0) | 2026.02.08 |
Comments
