242. Valid Anagram

Doyeon Kim·2022년 5월 25일

코딩테스트 공부

목록 보기
68/171

문제 링크 : https://leetcode.com/problems/valid-anagram/


두 문자열 s와 t가 서로 anagram이면 true, 아니면 False를 반환하는 문제이다.

anagram이란? 한 단어의 철자를 분해해 다른 단어, 혹은 다른 문장으로 바꾸는 놀이를 뜻한다고 한다.
ex. tan -> ant 은 아나그램 맞음(참)
rat -> cat은 아님

문제를 이해하자마자 가장 먼저 떠오른 방법은 문자를 오름차순으로 정렬(문자는 알파벳 순?으로 정렬된다)하여 비교하는 방법이었다.
그래서 sorted()를 이용하여 간단하게 해결할 수 있었다.

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        
        sss = sorted(s)
        ttt = sorted (t)
        
        if sss == ttt:
            return True
        return False
        

Runtime: 53 ms, faster than 79.48% of Python3 online submissions for Valid Anagram.
Memory Usage: 15.1 MB, less than 21.92% of Python3 online submissions for Valid Anagram.
Time complexity: O(n log n)


다른 방법들을 찾아보니 파이썬 내부의 collection함수를 이용해서 푸는 방법과 dictionary를 이용하는 방법들이 있었다


01.08.22

이번에는 dictonary를 이용하여 다른 방법으로 퓰어보았다

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        dics = {}
        dictt={}
        
        for i in s : 
            dics[i] = dics.get(i,0)+1
        for i in t:
            dictt[i] = dictt.get(i,0)+1
        
        return dics == dictt

get() : 첫 번째 인자로는 찾고자 하는 키를 넣는다. 먼저 ]그리고는 콤마(,)를 하고 두 번째 인자로는 첫 번째 인자에서 넣은 키가 없을 때 넣고자 하는 값을 넣는다.

profile
성장하고 도전하는 개발자. 프로그래밍 좋아하세요?

0개의 댓글