5月挑战Day3-Ransom Note

本文探讨了如何判断一个字符串是否能由另一个字符串中的字符组成,重点介绍了两种解法:一是通过字典统计字符频率,二是利用Python的collections.Counter类进行高效计算。

Day3-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.

字符串匹配问题,magazine的字符串中的字符是否能组成ransomNote的字符。有一个限制条件是magazine中的字符和ransomNote中的字符是一一对应的,也就是不存在多对一的关系,重复的情况是不存在的。就是例子中第二个那种,ransomNote中有两个a,magazine中也得有两个a.

Example:

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

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

解法一:

以空间换时间,我们设置两个字典分别存储两个字符串中字符出现的次数,然后遍历ransom字典,如果该元素在magazine字典中没有返回False,如果在magazine字典中出现的次数少于ransom字典的次数返回False.

class Solution:
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
        ran_dict = {}
        magazine_dict = {}
        for i in ransomNote:
            if i in ran_dict:
                ran_dict[i] += 1
            else:
                ran_dict[i] = 0
        for i in magazine:
            if i in magazine_dict:
                magazine_dict[i] += 1
            else:
                magazine_dict[i] = 0
        for i in ran_dict:
            if i in magazine_dict:
                if magazine_dict[i] < ran_dict[i]:
                    return False
            else:
                return False
        return True

m-len(ransom),n-len(magazine)时间复杂度维O(m).空间复杂度维O(n + m).

解法二:

和上面那种一样,只不过用到了python中collection中的counter类,它是字典的子类,主要是实现计数功能,我们用他来对两个字符串分别计数,然后再相减取反就可以了,相减返回的是值为正值的元素,这样如果magazine的元素次数比ransom的少,返回的为正值我们就取反为false。

class Solution:
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
        ransomCnt = collections.Counter(ransomNote)
        print(ransomCnt)
        magazineCnt = collections.Counter(magazine)
        print(magazineCnt)
        print(ransomCnt - magazineCnt)
        return not ransomCnt - magazineCnt
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值