题目要求:
给你两个字符串:ransomNote 和 magazine ,判断 ransomNote 能不能由 magazine 里面的字符构成。
如果可以,返回 true ;否则返回 false 。
magazine 中的每个字符只能在 ransomNote 中使用一次。
示例 1:
输入:ransomNote = "a", magazine = "b"
输出:false
解题思路:
如果magazine的长度小于ransomNote的长度,不能构成,返回false,否则统计两个字符串中字母出现的次数,如果magazine的字母次数都大于等于ransomNote,返回true
代码展示:
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
if len(magazine)<len(ransomNote):
return False
return not collections.Counter(ransomNote)-collections.Counter(magazine)
运行结果: