题目用时
类型:简单
时长:1.5H
题目场景
No.383.给定一个赎金信 (ransom) 字符串和一个杂志(magazine)字符串,判断第一个字符串 ransom 能不能由第二个字符串 magazines 里面的字符构成。如果可以构成,返回 true ;否则返回 false。
(题目说明:为了不暴露赎金信字迹,要从杂志上搜索各个需要的字母,组成单词来表达意思。杂志字符串中的每个字符只能在赎金信字符串中使用一次。)
注意:
你可以假设两个字符串均只含有小写字母
题目分析
审题很重要,根据自己的思路首先分析这是一个什么问题,转化为你认识的可以解决问题的方法
# ======条件分析======
# 赎金信ransom string1 杂志magazine string2
# string1 string2 都只有小写字母
# string2 中的字符是否可以构成 string1
# string2 中的字符只能使用1次 构成 string1
# 能 True 不能 False
# ======结题思路======
# 1.string1字符串进行拆分成一个个的 string不能直接拆分 所以使用list()
# 2.由于string2中的字符串每个只能使用1次 所以string1每取一个匹配一个string2的
# 3.第一层遍历用string1取1个 第二层进行匹配 if True 继续 if false 结束返回false
自己思路解题
注意:这里的类名,函数名都是Leetcode定义好的,否则没法提交测试
class Solution:
def canConstruct(self, string1, string2):
# 1. list()类型转换
list1 = list(string1)
list2 = list(string2)
# 2. 存在str为空的情况先判断
if len(list1) != 0:
# 3. 取string1
for r in list1:
if len(list2) != 0:
long = len(list2)
i = 1
# 4. 取string2
for m in list2:
if r == m:
a = list2.index(m)
del list2[a]
i += 1
break
else:
if i == long:
return False
else:
i += 1
continue
else:
return False
else:
if list1 == list2:
return True
return True
学习别人解题
思路一
结论:对python的基础语法掌握不牢固
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
ran = list(ransomNote)
mag = list(magazine)
for i in ran:
# 直接对mag是否在ran中进行判断,python独有的判断方式,可是自己却忽略了
if i in mag:
mag.remove(i)
else:
return False
return True
知识点补充:
思路二:
结论:基础数据类型的方法掌握遗忘
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
Hash_ran, Hash_mag = {}, {}
# 这里默认遍历的是 字典的key值
# 第一步 将两个字符串转化都转化为字典-->存储key对应的value个数
for i in ransomNote:
Hash_ran[i] = Hash_ran.get(i, 0) + 1
print(Hash_ran)
for j in magazine:
Hash_mag[j] = Hash_mag.get(j, 0) + 1
print(Hash_mag)
# 第二步 将Hashran中的key去取出来 进行遍历 让两个字典取值判断
for key in Hash_ran.keys():
# 如果 mag某个字符的个数小与ran中的则返回false
if Hash_mag.get(key, 0) < Hash_ran[key]:
return False
return True
# 输入
{'f': 4, 'd': 2, 's': 2, 'a': 2}
{'f': 4, 'd': 2, 's': 3, 'a': 2}
# 返回
True
知识点补充:
dict.get(key, default=None)
- key – 字典中要查找的键
- default – 如果指定键的值不存在时,返回该默认值
思路三:
之前完全没有接触过collection类
import collections
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
# 这里的结题逻辑就是思路二的逻辑类似地用collection的Counter方法实现了出来
return False if collections.Counter(ransomNote) - collections.Counter(magazine) else True
# a = Solution().canConstruct('fdsffff', 'fdsff')
# print(a)
# 对collection.Counter方法的认识尝试
a = ['red', 'blue', 'red', 'green', 'blue', 'blue']
print(collections.Counter(a))
b = ['red', 'blue', 'red', 'green', 'blue', 'blue', 'hello']
print(collections.Counter(b))
c = collections.Counter(a) - collections.Counter(b)
print(c)
# print(collections.Counter(a)-collections.Counter(b))
# print(type(collections.Counter(a)-collections.Counter(b)))
print(bool(collections.Counter()))
print(bool(list()))
知识点补充:
collections —> Container datatypes 容器数据类型
作用:一个Counter 是一个dict的子类,用于***计数可哈希对象***。它是一个集合,元素像字典键(key)一样存储,它们的计数存储为值。计数可以是任何整数值,包括0和负数。Counter类有点像其他语言中的 bags或multisets。