LeetCode刷题实战383:赎金信
Given two stings ransomNote and magazine, return true if ransomNote can be constructed from magazine and false otherwise.
Each letter in magazine can only be used once in ransomNote.
示例
示例 1:
输入:ransomNote = "a", magazine = "b"
输出:false
示例 2:
输入:ransomNote = "aa", magazine = "ab"
输出:false
示例 3:
输入:ransomNote = "aa", magazine = "aab"
输出:true
解题
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
a = {}
for i in magazine:
if i not in a:
a[i] = 1
else:
a[i] += 1
for j in ransomNote:
if j not in a:
return False
else:
a[j] -= 1
if a[j] < 0:
return False
return True