原文链接: https://leetcode-cn.com/problems/uncommon-words-from-two-sentences
英文原文
A sentence is a string of single-space separated words where each word consists only of lowercase letters.
A word is uncommon if it appears exactly once in one of the sentences, and does not appear in the other sentence.
Given two sentences s1
and s2
, return a list of all the uncommon words. You may return the answer in any order.
Example 1:
Input: s1 = "this apple is sweet", s2 = "this apple is sour" Output: ["sweet","sour"]
Example 2:
Input: s1 = "apple apple", s2 = "banana" Output: ["banana"]
Constraints:
1 <= s1.length, s2.length <= 200
s1
ands2
consist of lowercase English letters and spaces.s1
ands2
do not have leading or trailing spaces.- All the words in
s1
ands2
are separated by a single space.
中文题目
句子 是一串由空格分隔的单词。每个 单词 仅由小写字母组成。
如果某个单词在其中一个句子中恰好出现一次,在另一个句子中却 没有出现 ,那么这个单词就是 不常见的 。
给你两个 句子 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 <= 200
s1
和s2
由小写英文字母和空格组成s1
和s2
都不含前导或尾随空格s1
和s2
中的所有单词间均由单个空格分隔
通过代码
官方题解
方法:计数
思路和算法
每个不常见的单词总共只出现一次。我们可以统计每个单词的出现次数,然后返回恰好出现一次的单词。
[xehjDBgG-Java]class Solution { public String[] uncommonFromSentences(String A, String B) { Map<String, Integer> count = new HashMap(); for (String word: A.split(" ")) count.put(word, count.getOrDefault(word, 0) + 1); for (String word: B.split(" ")) count.put(word, count.getOrDefault(word, 0) + 1); List<String> ans = new LinkedList(); for (String word: count.keySet()) if (count.get(word) == 1) ans.add(word); return ans.toArray(new String[ans.size()]); } }
[xehjDBgG-Python]class Solution(object): def uncommonFromSentences(self, A, B): count = {} for word in A.split(): count[word] = count.get(word, 0) + 1 for word in B.split(): count[word] = count.get(word, 0) + 1 #Alternatively: #count = collections.Counter(A.split()) #count += collections.Counter(B.split()) return [word for word in count if count[word] == 1]
复杂度分析
时间复杂度:$O(M + N)$,其中 $M, N$ 分别是
A
和B
的长度。空间复杂度:$O(M + N)$,
count
所用去的空间。
统计信息
通过次数 | 提交次数 | AC比率 |
---|---|---|
20337 | 30686 | 66.3% |
提交历史
提交时间 | 提交结果 | 执行时间 | 内存消耗 | 语言 |
---|