카테고리 없음

[LeetCode/Python] 383. Ransome Note

빵빵0 2024. 9. 11. 00:12

문제 링크: https://leetcode.com/problems/ransom-note/description/?envType=study-plan-v2&envId=top-interview-150

 

[풀이 코드]

class Solution:
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
        # letter -> int
        book = {}

        for letter in magazine:
            if letter in book:
                book[letter] += 1
            else:
                book[letter] = 1
        
        for letter in ransomNote:
            if letter not in book:
                return False
            elif book[letter] == 0:
                return False
            else:
                book[letter] -= 1

        return True

 

 

 

[다른 사람 풀이]

class Solution(object):
    def canConstruct(self, ransomNote, magazine):
        st1, st2 = Counter(ransomNote), Counter(magazine)
        if st1 & st2 == st1:
            return True
        return False

Counter 사용!

 

class Solution(object):
    def canConstruct(self, ransomNote, magazine):
        
        chars = {}
        for char in magazine:
            if char not in chars: chars[char] = 1
            else: chars[char] += 1

        for char in ransomNote:
            if char in chars and chars[char] > 0: chars[char] -= 1
            else: return False
        
        return True

나랑 비슷하지만 코드가 깔끔하다!

 

 

시간복잡도

추후 작성