LeetCode 题解工作台
赎金信
给你两个字符串: ransomNote 和 magazine ,判断 ransomNote 能不能由 magazine 里面的字符构成。 如果可以,返回 true ;否则返回 false 。 magazine 中的每个字符只能在 ransomNote 中使用一次。 示例 1: 输入: ransomN…
3
题型
7
代码语言
3
相关题
当前训练重点
简单 · 哈希·表·结合·string
答案摘要
我们可以用一个哈希表或长度为 的数组 记录字符串 `magazine` 中所有字符出现的次数。然后遍历字符串 `ransomNote`,对于其中的每个字符 ,我们将其从 的次数减 ,如果减 之后的次数小于 ,说明 在 `magazine` 中出现的次数不够,因此无法构成 `ransomNote`,返回 即可。 否则,遍历结束后,说明 `ransomNote` 中的每个字符都可以在 `m…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 哈希·表·结合·string 题型思路
题目描述
给你两个字符串: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 <= 105ransomNote和magazine由小写英文字母组成
解题思路
方法一:哈希表或数组
我们可以用一个哈希表或长度为 的数组 记录字符串 magazine 中所有字符出现的次数。然后遍历字符串 ransomNote,对于其中的每个字符 ,我们将其从 的次数减 ,如果减 之后的次数小于 ,说明 在 magazine 中出现的次数不够,因此无法构成 ransomNote,返回 即可。
否则,遍历结束后,说明 ransomNote 中的每个字符都可以在 magazine 中找到对应的字符,因此返回 。
时间复杂度 ,空间复杂度 。其中 和 分别为字符串 ransomNote 和 magazine 的长度;而 为字符集的大小,本题中 。
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
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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).