LeetCode 题解工作台

两句话中的不常见单词

句子 是一串由空格分隔的单词。每个 单词 仅由小写字母组成。 如果某个单词在其中一个句子中恰好出现一次,在另一个句子中却 没有出现 ,那么这个单词就是 不常见的 。 给你两个 句子 s1 和 s2 ,返回所有 不常用单词 的列表。返回列表中单词可以按 任意顺序 组织。 示例 1: 输入: s1 = …

category

3

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

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

bolt

答案摘要

根据题目描述,只要单词出现一次,就符合题目要求。因此,我们用哈希表 记录所有单词以及出现的次数。 然后遍历哈希表,取出所有出现次数为 的字符串即可。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

句子 是一串由空格分隔的单词。每个 单词 仅由小写字母组成。

如果某个单词在其中一个句子中恰好出现一次,在另一个句子中却 没有出现 ,那么这个单词就是 不常见的

给你两个 句子 s1s2 ,返回所有 不常用单词 的列表。返回列表中单词可以按 任意顺序 组织。

 

示例 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 <= 200
  • s1s2 由小写英文字母和空格组成
  • s1s2 都不含前导或尾随空格
  • s1s2 中的所有单词间均由单个空格分隔
lightbulb

解题思路

方法一:哈希表

根据题目描述,只要单词出现一次,就符合题目要求。因此,我们用哈希表 cntcnt 记录所有单词以及出现的次数。

然后遍历哈希表,取出所有出现次数为 11 的字符串即可。

时间复杂度 O(m+n)O(m + n),空间复杂度 O(m+n)O(m + n)。其中 mmnn 分别是字符串 s1s1s2s2 的长度。

1
2
3
4
5
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]
speed

复杂度分析

指标
时间O(M + N)
空间O(M + N)
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

两句话中的不常见单词题解:哈希·表·结合·string | LeetCode #884 简单