☀(day49:P46)
目录
📝题目:
给你两个字符串:ransomNote 和 magazine ,判断 ransomNote 能不能由 magazine 里面的字符构成。如果可以,返回 true ;否则返回 false 。
magazine 中的每个字符只能在 ransomNote 中使用一次。
⭐示例 1:
输入:ransomNote = "a", magazine = "b"
输出:false
⭐示例 2:
输入:ransomNote = "aa", magazine = "ab"
输出:false
⭐示例 3:
输入:ransomNote = "aa", magazine = "aab"
输出:true
🚩题目分析:
根据题意,首先我们知道的是当ransomNote字符串的长度大于 magazine字符串的长度或者 ransomNote中含有 magazine中没有的字符时 , ransomNote 肯定不能由 magazine 里面的字符构成。
💡解题思路:
判断ransomNote 能不能由 magazine 里面的字符构成本质是判断ransomNote中每个字符都能在magazine中找到,且ransomNote中每个字符s出现的次数都小于magazine中每个字符s出现的次数。
那么我们则可以根据该条件判断ransomNote 能不能由 magazine构成。
🌈代码实现
def canConstruct(ransomNote, magazine):
from collections import Counter
dct_r = dict(Counter(ransomNote))
dct_m = dict(Counter(magazine))
for i in ransomNote:
if i not in dct_m or dct_r[i] > dct_m[i]:
return False
return True
✏代码注释
def canConstruct(ransomNote, magazine):
# 导入Counter函数用于统计ransomNote, magazine中
# 每个字符出现的次数
from collections import Counter
# 以字典形式记录ransomNote中每个字符出现的次数
dct_r = dict(Counter(ransomNote))
# 以字典形式记录magazine中每个字符出现的次数
dct_m = dict(Counter(magazine))
for i in ransomNote:
# 判断字符i是否在magazine中和判断字符i在ransomNote中
# 出现的次数是否大于在magazine出现的次数
if i not in dct_m or dct_r[i] > dct_m[i]:
return False
return True
Conter函数用于统计元素出现的次数。
如
a = 'aabccc' lst = (Counter(a)) print(lst)
输出
Counter({'c': 3, 'a': 2, 'b': 1})
我们使用dict()将其转化为字典
a = 'aabccc' lst = dict(Counter(a)) print(lst)
输出
{'a': 2, 'b': 1, 'c': 3}
✨代码实现
因为用于统计元素出现次数的Counter是可以相减的。
如
a = 'aabccc' b = 'aabcc' print(Counter(a) - Counter(b))输出
Counter({'c': 1})
所以我们可以直接使用
Counter(ransomNote) - Counter(magazine)如果ransomNote中个字符s出现的次数都大于magazine中每个字符s出现的次数。
则Counter(ransomNote) - Counter(magazine)的结果为Counter()
如
a = 'abc' b = 'aabcc' print(Counter(a) - Counter(b))输出
Counter()
🌈代码实现
def canConstruct(ransomNote, magazine):
from collections import Counter
if len(ransomNote) > len(magazine):
return False
return not Counter(ransomNote) - Counter(magazine)
今天就到这,明天见。🚀
❄❄❄❄❄❄❄❄❄❄❄❄❄❄❄❄❄❄❄❄end❄❄❄❄❄❄❄❄❄❄❄❄❄❄❄❄❄❄❄❄❄❄❄❄❄❄