LeetCode 题解工作台
举报垃圾信息
给你一个字符串数组 message 和一个字符串数组 bannedWords 。 如果数组中 至少 存在两个单词与 bannedWords 中的任一单词 完全相同 ,则该数组被视为 垃圾信息 。 如果数组 message 是垃圾信息,则返回 true ;否则返回 false 。 示例 1: 输入: …
3
题型
5
代码语言
3
相关题
当前训练重点
中等 · 数组·哈希·扫描
答案摘要
我们用一个哈希表 存储 中的所有单词,然后遍历 中的每个单词,如果单词在哈希表 中出现,我们就将计数器 加一,如果 大于等于 ,我们就返回 ,否则返回 。 时间复杂度 $O((n + m) \times |w|)$,空间复杂度 $O(m \times |w|)$。其中 是数组 的长度,而 和 分别是数组 的长度和数组中单词的最大长度。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你一个字符串数组 message 和一个字符串数组 bannedWords。
如果数组中 至少 存在两个单词与 bannedWords 中的任一单词 完全相同,则该数组被视为 垃圾信息。
如果数组 message 是垃圾信息,则返回 true;否则返回 false。
示例 1:
输入: message = ["hello","world","leetcode"], bannedWords = ["world","hello"]
输出: true
解释:
数组 message 中的 "hello" 和 "world" 都出现在数组 bannedWords 中。
示例 2:
输入: message = ["hello","programming","fun"], bannedWords = ["world","programming","leetcode"]
输出: false
解释:
数组 message 中只有一个单词("programming")出现在数组 bannedWords 中。
提示:
1 <= message.length, bannedWords.length <= 1051 <= message[i].length, bannedWords[i].length <= 15message[i]和bannedWords[i]都只由小写英文字母组成。
解题思路
方法一:哈希表
我们用一个哈希表 存储 中的所有单词,然后遍历 中的每个单词,如果单词在哈希表 中出现,我们就将计数器 加一,如果 大于等于 ,我们就返回 ,否则返回 。
时间复杂度 ,空间复杂度 。其中 是数组 的长度,而 和 分别是数组 的长度和数组中单词的最大长度。
class Solution:
def reportSpam(self, message: List[str], bannedWords: List[str]) -> bool:
s = set(bannedWords)
return sum(w in s for w in message) >= 2
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for the candidate's ability to implement efficient searching using a hash set.
- question_mark
Evaluate the candidate's approach to optimizing for early exits.
- question_mark
Test the candidate's understanding of time complexity, particularly with large arrays.
常见陷阱
外企场景- error
Incorrect handling of case sensitivity: The problem specifies lowercase letters only, but candidates might mistakenly use case-insensitive checks.
- error
Not using a hash set: A naive approach without hash sets could lead to slow performance for large inputs.
- error
Failing to optimize for early exit: Checking the entire array even after finding two banned words is inefficient.
进阶变体
外企场景- arrow_right_alt
Instead of returning true or false, return the list of banned words found in the message.
- arrow_right_alt
Handle edge cases where the `message` or `bannedWords` arrays are empty.
- arrow_right_alt
Optimize for constant space complexity by scanning the array and checking banned words inline without using a hash set.