Leetcode原题链接:赎金信
零、暴力解法
练了不少哈希表,已经成长了,第一时间没有想要使用暴力解法 : D
一、哈希表解法
1、分析
- 先把 magazine 里的字符一个个存入字典中:{字符:次数}。
- 遍历 ransomNote 里的字符,若不存在则返回 False ,若存在但是次数为 0 则返回False,次数不为 0 则次数减一。
- 顺利跳出循环则返回 True 。
2、代码
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
hashmap = {}
for i in magazine:
if i in hashmap:
hashmap[i] += 1
else:
hashmap[i] = 1
for j in ransomNote:
if j not in hashmap:
return False
else:
if hashmap[j] == 0:
return False
else:
hashmap[j] -= 1
return True
二、第一次见的函数
1、collections.Counter
哈希表在python中可以用collections.Counter计数来体现。
该方法用于统计某序列中每个元素出现的次数,以键值对的方式存在字典中。但类型其实是Counter。
nums = [1, 2, 3, 1, 2, 1]
counts = collections.Counter(nums)
print(counts)
# Counter({1: 3, 2: 2, 3: 1})
2、本题实现代码
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
c1 = collections.Counter(ransomNote)
c2 = collections.Counter(magazine)
x = c1 - c2
#x只保留值大于0的符号,当c1里面的符号个数小于c2时,不会被保留
#所以x只保留下了,magazine不能表达的
if(len(x) == 0):
return True
else:
return False