Algorithm/Leetcode
[Top Interview 150 - Hashmap] 383. Ransom Note
code-bean
2024. 10. 12. 20:04
[Q] [Easy]
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 ransomNote.
- Hash 문제는 익숙해지는 것이 중요한 것 같다.
- dict.get() 만 알면 수월하게 풀 수 있었던 문제
# Answer
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
char_frequency = dict()
for char in magazine:
char_frequency[char] = char_frequency.get(char, 0) + 1
for char in ransomNote:
if char_frequency.get(char, 0) == 0 :
return False
char_frequency[char] -= 1
return True