383. Ransom Note
Hash Table, String, Counting ·Problem Statement
link: LeetCode.cn LeetCode
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.
Example:
Input: ransomNote = "a", magazine = "b"
Output: false
Input: ransomNote = "aa", magazine = "ab"
Output: false
Input: ransomNote = "aa", magazine = "aab"
Output: true
Solution Approach
Algorithm
Implement
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
m_count = collections.Counter(magazine)
r_count = collections.Counter(ransomNote)
for k, v in r_count.items():
if k not in m_count:
return False
if m_count[k] < v:
return False
return True