LeetCode 题解工作台
两句话中的不常见单词
句子 是一串由空格分隔的单词。每个 单词 仅由小写字母组成。 如果某个单词在其中一个句子中恰好出现一次,在另一个句子中却 没有出现 ,那么这个单词就是 不常见的 。 给你两个 句子 s1 和 s2 ,返回所有 不常用单词 的列表。返回列表中单词可以按 任意顺序 组织。 示例 1: 输入: s1 = …
3
题型
7
代码语言
3
相关题
当前训练重点
简单 · 哈希·表·结合·string
答案摘要
根据题目描述,只要单词出现一次,就符合题目要求。因此,我们用哈希表 记录所有单词以及出现的次数。 然后遍历哈希表,取出所有出现次数为 的字符串即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 哈希·表·结合·string 题型思路
题目描述
句子 是一串由空格分隔的单词。每个 单词 仅由小写字母组成。
如果某个单词在其中一个句子中恰好出现一次,在另一个句子中却 没有出现 ,那么这个单词就是 不常见的 。
给你两个 句子 s1 和 s2 ,返回所有 不常用单词 的列表。返回列表中单词可以按 任意顺序 组织。
示例 1:
输入:s1 = "this apple is sweet", s2 = "this apple is sour" 输出:["sweet","sour"]
示例 2:
输入:s1 = "apple apple", s2 = "banana" 输出:["banana"]
提示:
1 <= s1.length, s2.length <= 200s1和s2由小写英文字母和空格组成s1和s2都不含前导或尾随空格s1和s2中的所有单词间均由单个空格分隔
解题思路
方法一:哈希表
根据题目描述,只要单词出现一次,就符合题目要求。因此,我们用哈希表 记录所有单词以及出现的次数。
然后遍历哈希表,取出所有出现次数为 的字符串即可。
时间复杂度 ,空间复杂度 。其中 和 分别是字符串 和 的长度。
class Solution:
def uncommonFromSentences(self, s1: str, s2: str) -> List[str]:
cnt = Counter(s1.split()) + Counter(s2.split())
return [s for s, v in cnt.items() if v == 1]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(M + N) |
| 空间 | O(M + N) |
面试官常问的追问
外企场景- question_mark
The candidate demonstrates understanding of hash tables for counting word frequencies.
- question_mark
The candidate should be able to implement the filtering of uncommon words efficiently.
- question_mark
The candidate should be aware of handling edge cases, like repeated words within a sentence.
常见陷阱
外企场景- error
Not correctly handling words that appear more than once in either sentence.
- error
Failing to account for cases where no uncommon words exist.
- error
Incorrectly counting words, missing one of the sentences, or not using hash tables properly for counting.
进阶变体
外企场景- arrow_right_alt
Modify the problem to return words that appear exactly twice in each sentence.
- arrow_right_alt
Handle cases where multiple uncommon words exist but with a higher frequency.
- arrow_right_alt
Optimize the solution for larger datasets by considering more advanced data structures.