알고리즘/LeetCode

LeetCode 242. Valid Anagram

Timha 2023. 9. 1. 00:49

 

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.

 

 

풀이

 

아나그램은 두 단어가 다르지만  동일한 알파벳과 개수로 구성된 단어이다 .

 

 

1.정렬로 푸는 방법 

문제를 보고 정렬시켜서 풀면 쉽겠다 생각하고 정렬함수를 사용하여 문제를 풀었다. 

문자열은 순회가 가능하니,  정렬 후 동일한지 확인해주는 방법으로 풀었다,

class Solution(object):
    def isAnagram(self, s, t):
        if sorted(s) == sorted(t):
            return True
        
        return False

2. 해시테이블로 풀는 방법

 

전에 풀었던 383. Ransom Note 문제에서 풀었던 s의 각 문자열을 for문으로 딕셔너리에 개수를 넣어주고,

t의 문자열을 for문으로 순회하며 -1시켜준다, 존재하지 않는다면 False를 반환한다.

 이후에 딕셔너리의 key value를 모두 꺼내서 value가 0이상이라면 False를 반환한다, .items() 함수를 사용안하고 그냥 dict.value()로 뽑아서 사용해도 상관없다. 

 

 

class Solution(object):
    def isAnagram(self, s, t):
        dict ={}
        for i in s:
            if i not in dict:
                dict[i] = 1
            else:
                dict[i]+=1
        
        for i in t:
            if i not in dict or dict[i]==0:
                return False
            dict[i]-=1
            
        for key,value in dict.items():
            if value >0:
                return False
        
        return True

 

 

다른사람의 코드 

1.    
    def isAnagram(self, s, t):
        dictionary = {}
        
        for i in s:
            if i in dictionary:
                dictionary[i] += 1
            else:
                dictionary[i] = 1

        for i in t:
            if i in dictionary:
                dictionary[i] -= 1
            else:
                return False

        for val in dictionary.values():
            if val != 0:
                return False
        
        return True
        
        
   2.
   class Solution(object):
    def isAnagram(self, s, t):
        return sorted(s.strip()) == sorted(t.strip())

둘 다 나랑 같은 생각을 했다..ㅎㅎ