LeetCode 题解工作台

赎金信

给你两个字符串: ransomNote 和 magazine ,判断 ransomNote 能不能由 magazine 里面的字符构成。 如果可以,返回 true ;否则返回 false 。 magazine 中的每个字符只能在 ransomNote 中使用一次。 示例 1: 输入: ransomN…

category

3

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 哈希·表·结合·string

bolt

答案摘要

我们可以用一个哈希表或长度为 的数组 记录字符串 `magazine` 中所有字符出现的次数。然后遍历字符串 `ransomNote`,对于其中的每个字符 ,我们将其从 的次数减 ,如果减 之后的次数小于 ,说明 在 `magazine` 中出现的次数不够,因此无法构成 `ransomNote`,返回 即可。 否则,遍历结束后,说明 `ransomNote` 中的每个字符都可以在 `m…

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 哈希·表·结合·string 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你两个字符串:ransomNotemagazine ,判断 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 <= 105
  • ransomNotemagazine 由小写英文字母组成
lightbulb

解题思路

方法一:哈希表或数组

我们可以用一个哈希表或长度为 2626 的数组 cntcnt 记录字符串 magazine 中所有字符出现的次数。然后遍历字符串 ransomNote,对于其中的每个字符 cc,我们将其从 cntcnt 的次数减 11,如果减 11 之后的次数小于 00,说明 ccmagazine 中出现的次数不够,因此无法构成 ransomNote,返回 falsefalse 即可。

否则,遍历结束后,说明 ransomNote 中的每个字符都可以在 magazine 中找到对应的字符,因此返回 truetrue

时间复杂度 O(m+n)O(m + n),空间复杂度 O(C)O(C)。其中 mmnn 分别为字符串 ransomNotemagazine 的长度;而 CC 为字符集的大小,本题中 C=26C = 26

1
2
3
4
5
6
7
8
9
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
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Checks for efficient handling of string operations and hash table manipulation.

  • question_mark

    Evaluates understanding of counting characters and early termination optimization.

  • question_mark

    Tests ability to correctly implement hash table usage and manage frequency comparisons.

warning

常见陷阱

外企场景
  • error

    Incorrectly assuming that characters can be reused from the magazine when they can only be used once.

  • error

    Failing to account for the scenario where a character in the ransomNote does not appear enough times in the magazine.

  • error

    Overcomplicating the solution by using unnecessary data structures or algorithms, instead of leveraging a simple hash table or frequency map.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    What if the magazine and ransomNote contain uppercase letters? Modify the hash table to account for both cases.

  • arrow_right_alt

    Extend the problem to handle more complex scenarios like punctuations or numbers. How would the approach change?

  • arrow_right_alt

    Consider the impact on performance if the input strings were significantly larger (e.g., with lengths up to 10^6).

help

常见问题

外企场景

赎金信题解:哈希·表·结合·string | LeetCode #383 简单