알고리즘 스터디

[Leetcode/파이썬] 242. Valid Anagram

난쟁이 개발자 2025. 9. 22. 16:51
반응형

Valid Anagram

Difficulty: Easy


Given two strings s and t, return true if t is an anagram of s, and false otherwise.

 

Example 1:

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

Output: true

Example 2:

Input: s = "rat", t = "car"

Output: false

 

Constraints:

  • 1 <= s.length, t.length <= 5 * 104
  • s and t consist of lowercase English letters.

 

Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?

 

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        if len(s) != len(t) :
            return False
        
        words = {}

        for char in s :
            words[char] = words.get(char, 0) + 1
        
        for char in t :
            if char not in words or words[char] == 0 :
                return False
            words[char] -= 1
        
        return True

당연히 s.sort(), t.sort()로 해도 해결된다. 그러나 조금 더 문제의 취지에 맞게 해결해보자. 지금 문제에서는 영어 소문자만 취급한다고 되어있지만, Follow up 에서 유니코드가 포함되어 있다면? 이라고 나온다. 그런 점에서 하나하나 비교해가면서 하는 것이 더 낫다고 판단된다. 

아나그램을 알아보자. 문자의 순서와 관계없이 같은 요소로 구성된 문제들을 말한다. 그렇기 때문에 s의 각 문자를 세서 딕셔너리에 알파벳 : 갯수로 키-밸류로 구성하고 t의 각 문자마자 해당 문자가 words에 속해있지 않거나, 해당 문자가 words 내에서 0개 라면, 아나그램 조건에 부합하지 않기 때문에 False 처리를 하고 문자를 하나씩 제거한다. 

최종 완료 하게 되면 True를 반환한다. 

이 문제는 예시를 조금 유심히 보면 쉽게 해결할 수 있을 것이다. 

반응형