본문 바로가기

자료구조,알고리즘

LeetCode-383 Ransom Note 파이썬 풀이

 

Ransom Note - LeetCode

Can you solve this real interview question? Ransom Note - Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters from magazine and false otherwise. Each letter in magazine can only be used once in ranso

leetcode.com

문제

문자열 magazine에 있는 문자들을 조합하여 ransomeNote 문자열을 만들 수 있는지 판별하는 문제입니다. magazine에 있는 문자들을 중복해서 사용할 수는 없습니다.

풀이

1. ransomNote를 순회합니다.

2. 만약 현재 위치한 ransomNote의 문자가 magazine안에 없다면 바로 false를 반환합니다.

3. 만약 현재 위치한 ransomeNote의 문자가 magazine안에 있다면 중복 사용될 수 없도록 magazine안의 해당 문자 딱 하나를 제거합니다.

4. ransomeNote 끝까지 반복합니다. 

5. ransomeNote의 끝까지 False 반환없이 실행했다면 ransomeNote를 조합할 수 있는 문자들이 모두 magazine 안에 존재한다는 의미가 되므로 True를 반환합니다.

class Solution:
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
        for element in ransomNote:
            if element in magazine:
                magazine = magazine.replace(element,"",1)
            else:
                return False
        return True