반응형
LeetCode 문제 해석 및 풀이 방법
문제 242. Valid Anagram (유효한 아나그)
문제 설명
영문
Given two strings s and t, return true if t is an anagram of s, and false otherwise.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
한글
두 문자열 s와 t를 입력받고, t가 s의 아나그램이면 True, 아니면 False를 반환하세요.
아나그램이란 일반적으로 모든 원래 문자를 정확히 한 번 사용하여 다른 단어나 구문의 문자를 재배열하여 형성된 단어나 구문입니다.
제한조건
- 1 <= s.length, t.length <= 5 * 104
- s and t consist of lowercase English letters.
입출력 예
입력 | 출력 |
s = "anagram", t = "nagaram" | true |
s = "rat", t = "car" | false |
해답 및 해설
파이썬 (Python)
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
s_dic = {}
t_dic = {}
for char in s:
s_dic[char] = s_dic.get(char, 0) + 1
for char in t:
t_dic[char] = t_dic.get(char, 0) + 1
return s_dic == t_dic
해쉬 테이블인 파이썬의 사전을 이용한 풀이
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return sorted(s) == sorted(t)
from collections import Counter
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return Counter(s) == Counter(t)
정렬이나 Countrer라는 파이썬 함수를 이용한 풀이도 있었다
반응형
'🖥️ 문제 풀이 > 리트코드(Leetcode)' 카테고리의 다른 글
[LeetCode 해석 및 풀이] 347. Top K Frequent Elements (0) | 2024.04.14 |
---|---|
[LeetCode 해석 및 풀이] 49. Group Anagrams (0) | 2024.04.11 |
[LeetCode 해석 및 풀이] 1. Two Sum (0) | 2024.04.11 |
[LeetCode 해석 및 풀이] 217. Contains Duplicate (0) | 2024.04.11 |
Neetcode 코딩 테스트 로드맵 (0) | 2024.04.11 |
댓글