몰입공간

[Leetcode] 242. Valid Anagram (python) 본문

Algorithm/Leetcode

[Leetcode] 242. Valid Anagram (python)

sahayana 2023. 8. 30. 20:11

#1.  문제

https://leetcode.com/problems/valid-anagram

 

Valid Anagram - LeetCode

Can you solve this real interview question? 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

leetcode.com

 

 

문자열 s와 t가 주어질 때, t가 s의 애너그램인지 확인하는 문제

 

Input: 
s = "anagram"
t = "nagaram"

Output: 
true

Explanation:
t를 재조합하면 anagram과 같다.

 

 


#2.  풀이

 

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        s, t = s.lower(), t.lower()
        return sorted(s) == sorted(t)

 

이전에 애너그램 관련 문제를 풀어봐서 쉬웠다.애너그램은 문자를 재조합하여 다른 뜻을 만드는 것을 의미하는데 여기서 t를 재조합했을 때 s가 나오는지 보면 된다.

s를 정렬한 값과 t를 정렬한 값이 같다면 이는 애너그램이다.

Comments