Leetcode 383. 赎金信

383. 赎金信

Leetcode 383. 赎金信

一、题目描述

给你两个字符串:ransomNote 和 magazine ,判断 ransomNote 能不能由 magazine 里面的字符构成。

如果可以,返回 true ;否则返回 false 。

magazine 中的每个字符只能在 ransomNote 中使用一次。

示例 1:
输入:ransomNote = “a”, magazine = “b”
输出:false

示例 2:
输入:ransomNote = “aa”, magazine = “ab”
输出:false

示例 3:
输入:ransomNote = “aa”, magazine = “aab”
输出:true

提示:

  • 1 <= ransomNote.length, magazine.length <= 10^5
  • ransomNote 和 magazine 由小写英文字母组成

二、我的想法

原本是想着按着 Leetcode 392. 判断子序列这题的方法写,结果 102 / 128 个通过的测试用例。
没过的测试案例是

ransomNote = “aab”
magazine = “baa”

后来想想之前的做法不能用,那只能利用 defaultdict 来计数,将两个字符串中的字符进行计数。之后再循环遍历生成的 dict,看看 ransomNote 对应的字符数量是否小于 magazine 对应的字符数量,小于的话就返回 False。

class Solution:
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
        rCounter = defaultdict(int)
        mCounter = defaultdict(int)
        for r in ransomNote:
            rCounter[r] += 1
        for m in magazine:
            mCounter[m] += 1
        for k, v in rCounter.items():
            if mCounter[k] < v:
                return False
        return True

看了 ylb 的题解 [Python3/Java/C++/Go/TypeScript] 一题一解:哈希表或数组(清晰题解),还能这么想,真的牛。

class Solution:
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
        cnt = Counter(magazine)
        for c in ransomNote:
            cnt[c] -= 1
            if cnt[c] < 0:
                return False
        return True

相关推荐

  1. LeetCode383赎金

    2024-07-19 18:00:04       33 阅读
  2. LeetCode 383赎金

    2024-07-19 18:00:04       27 阅读
  3. Leetcode 383. 赎金

    2024-07-19 18:00:04       20 阅读
  4. LeetCode每日一题 | 383. 赎金

    2024-07-19 18:00:04       58 阅读
  5. 383. 赎金

    2024-07-19 18:00:04       57 阅读
  6. 383.赎金

    2024-07-19 18:00:04       41 阅读
  7. 383. 赎金

    2024-07-19 18:00:04       40 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-19 18:00:04       66 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-19 18:00:04       70 阅读
  3. 在Django里面运行非项目文件

    2024-07-19 18:00:04       57 阅读
  4. Python语言-面向对象

    2024-07-19 18:00:04       68 阅读

热门阅读

  1. 接口加密方案

    2024-07-19 18:00:04       18 阅读
  2. ubuntu24.04 搭建TFTP服务

    2024-07-19 18:00:04       19 阅读
  3. 39、PHP 实现二叉树的下一个结点(含源码)

    2024-07-19 18:00:04       18 阅读
  4. box-shadow

    2024-07-19 18:00:04       16 阅读
  5. 【理解Python中的字典推导式】

    2024-07-19 18:00:04       17 阅读
  6. Qt 遍历Combbox下拉框的内容并进行判断

    2024-07-19 18:00:04       17 阅读
  7. 数据库存 IP 地址,用什么数据类型比较好?

    2024-07-19 18:00:04       16 阅读
  8. linux报错-bash: ./xx.sh: Permission denied

    2024-07-19 18:00:04       15 阅读
  9. 网络安全等级保护制度是如何分级的?

    2024-07-19 18:00:04       19 阅读
  10. 【Leetcode】14. 最长公共前缀

    2024-07-19 18:00:04       17 阅读