[383] Ransom Note
https://leetcode.com/problems/ransom-note/description/
- algorithms
- Easy (48.72%)
- Source Code: 383.ransom-note.py
- Total Accepted: 107.8K
- Total Submissions: 217.6K
- Testcase Example: '"a"\n"b"'
Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false.
Each letter in the magazine string can only be used once in your ransom note.
Note: You may assume that both strings contain only lowercase letters.
canConstruct("a", "b") -> false canConstruct("aa", "ab") -> false canConstruct("aa", "aab") -> true
python
class Solution(object):
def canConstruct(self, ransomNote, magazine):
"""
:type ransomNote: str
:type magazine: str
:rtype: bool
"""
A, B = {}, {}
for m in magazine:
if m not in B:
B[m] = 0
B[m] += 1
for r in ransomNote:
if r not in A:
A[r] = 0
A[r] += 1
for k, v in A.items():
if not k in B or B[k] < v: return False
return True