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
'자료구조,알고리즘' 카테고리의 다른 글
LeetCode-150 Evaluate Reverse Polish Notation 파이썬 문제 풀이 (0) | 2023.09.01 |
---|---|
LeetCode-205 Isomorphic Strings 파이썬 풀이 (0) | 2023.09.01 |
LeetCode-219 Contains Duplicate II 파이썬 풀이 (0) | 2023.09.01 |
LeetCode-1 Two Sum 파이썬 풀이 (0) | 2023.09.01 |
LeetCode-155 MinStack 파이썬 풀이 (0) | 2023.09.01 |