BE/algorithm

[LeetCode] 242. Valid Anagram

bandal-gom 2022. 12. 14. 17:11

Intuition

  • Anagram은 주어진 문자열의 character를 재배치 했을 때에도 다 같은 구성의 character를 가지는 단어 혹은 문구를 뜻한다고 한다. 
    • 그러니 길이가 같아야지? 
  • 같은 구성의 character를 가져야하겠네?

Approach

  • 같은 구성의 문자를 가진것을 어떻게 비교하면 좋지? 
    • 정렬한 후에 같은지 확인하면 효율적이지 않을까
  • 길이가 다른 경우는 먼저 False를 반환 하는게 좋을 것 같다 

Complexity

Time complexity:

Space complexity:

  • O(1) 평균 / O(n) W.C 

Code

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        if len(s) != len(t): return False
        return sorted(s) == sorted(t)
반응형