leetcode 383. Ransom Note

本文详细解析了LeetCode上的第383题“赎金信”问题,介绍了如何判断一个字符串是否能由另一个字符串中的字符构成,并提供了三种不同实现方式的Python代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Python leetcode

leetcode  383. Ransom Note

Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false.

Each letter in the magazine string can only be used once in your ransom note.


这个题目理解起来比较难,我说的意思是英语不咋滴,有些单词不太明白,怎么还有ransomNote勒索信,杂志什么的?

网上看到一个这样的理解,我们要去分别一个信是不是通过杂志里面的文字造出来的,就和侦探中的破解密码一样,可能勒索信中的字是来自杂志的,这样组合就是勒索信息。这样大概理解一些了吧。


所以说白了,就是判断ransomNote中的字符满足两个条件1.ransomNote中的字符必须在magazine中出现2.ransomNote中的字符出现次数必须不超过magazine中对应的字符次数。


Note:
You may assume that both strings contain only lowercase letters.

canConstruct("a", "b") -> false
canConstruct("aa", "ab") -> false
canConstruct("aa", "aab") -> true



题目的意思:

题目的意思是第一个的字符串的每个字符必须在第二个字符串中,且第一个字符串中的字符次数小于第二个字符串中该字符的次数。


#coding=utf-8
class Solution():
    def canConstruct(self, ransomNote, magazine):#192ms
        from collections import Counter
        magDict=Counter(magazine)
        for letter in ransomNote:
            if letter not in magDict:
                return False
            else:
                magDict[letter]=magDict[letter]-1
                if  magDict[letter]<0:
                    return False
        return True

    def canConstruct1(self, ransomNote, magazine):#184ms
        from collections import Counter
        ranDict=Counter(ransomNote)
        magDict=Counter(magazine)
        for x in ranDict:
            if x not in magDict or ranDict[x]>magDict[x]:
                return False
        return True

    def canConstruct2(self, ransomNote, magazine):  #36ms
        from collections import  Counter
        return not Counter(ransomNote)-Counter(magazine)
    #Counter()的减法结果是前者中计数大于后者中,包括不存在后者中的
    #说白了就是相对于后者多的部分,就是前者中后者没有的或少的
    #若没有的话,就返回一个空的Counter()

s=Solution()
print s.canConstruct1('aabbbsd','aaabbbbwkskhd')



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值