본문 바로가기
🖥️ 문제 풀이/리트코드(Leetcode)

[LeetCode 해석 및 풀이] 242. Valid Anagram

by 뒬탕 2024. 4. 11.
반응형

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라는 파이썬 함수를 이용한 풀이도 있었다

반응형

댓글