383. ransom note 赎金信
一、刷题内容
原题链接
https://leetcode-cn.com/problems/ransom-note/
内容描述
给定一个赎金信 (ransom) 字符串和一个杂志(magazine)字符串,判断第一个字符串 ransom 能不能由第二个字符串 magazines 里面的字符构成。如果可以构成,返回 true ;否则返回 false。
(题目说明:为了不暴露赎金信字迹,要从杂志上搜索各个需要的字母,组成单词来表达意思。杂志字符串中的每个字符只能在赎金信字符串中使用一次。)
示例 1:
输入:ransomNote = “a”, magazine = “b”
输出:false
示例 2:
输入:ransomNote = “aa”, magazine = “ab”
输出:false
示例 3:
输入:ransomNote = “aa”, magazine = “aab”
输出:true
提示:
你可以假设两个字符串均只含有小写字母。
二、解题方法
1.方法一:remove函数
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
m = list(magazine)
for n in ransomNote:
if n not in m:
return False
m.remove(n)
return True
2.方法二:使用哈希表存储频数
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
m = collections.Counter(magazine)
for n in ransomNote:
if m[n] < 1:
return False
m[n] -= 1
return True
3.方法三:直接比较频数
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
freq_r = Counter(ransomNote)
freq_m = Counter(magazine)
for a in freq_r:
if a not in freq_m or freq_r[a]>freq_m[a]: return False
return True