[leetcode] 383. Ransom Note

本文详细解析了如何通过使用HashMap来解决赎金条问题,即判断一个字符串是否能由另一个字符串的字符组合而成,强调了每个字符在杂志字符串中只能被使用一次的原则。

Description

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.

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

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

分析

题目的意思是: 给定连个random字符串和一个magazine字符串,问random可不可以由magazine字符串组成。

  • 如果理解题意了,用一个map就可以搞定了,详情请看代码。

C++实现

class Solution {
public:
    bool canConstruct(string ransomNote, string magazine) {
        unordered_map<char, int> m;
        for(auto c:magazine){
            m[c]++;
        }
        for(auto c:ransomNote){
            if(--m[c]<0) return false;
        }
        return true;
    }
};

Python实现

思路就是用hash map实现,一个一个的比对。

class Solution:
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
        m = defaultdict(int)
        for ch in magazine:
            m[ch]+=1
        for ch in ransomNote:
            m[ch]-=1
            if m[ch]<0:
                return False
        return True

参考文献

[LeetCode] Ransom Note 赎金条

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值