1. 题目
2. 思路
直接用Python内置工具Counter
对字符串进行统计,然后比较值的范围即可。
3. 代码
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
target = Counter(ransomNote)
seed = Counter(magazine)
for key,val in target.items():
if val > seed[key]:
return False
return True
虽然上面这版代码可AC,但是体现了我对Counter
的不熟悉,其实代码还可以更简洁:
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
target = Counter(ransomNote)
seed = Counter(magazine)
return target <= seed