884. 两句话中的不常见单词

题目链接:https://leetcode-cn.com/problems/uncommon-words-from-two-sentences/

执行用时:2 ms, 在所有 Java 提交中击败了99.60% 的用户
内存消耗:39.9 MB, 在所有 Java 提交中击败了5.06% 的用户
通过测试用例:55 / 55

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

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

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

示例 1:

输入:s1 = “this apple is sweet”, s2 = “this apple is sour”
输出:[“sweet”,”sour”]

示例 2:

输入:s1 = “apple apple”, s2 = “banana”
输出:[“banana”]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
public String[] uncommonFromSentences(String s1, String s2) {
HashMap<String, Integer> map = new HashMap<>();
for (String retval: s1.split(" ")) {
if (map.containsKey(retval)) {
map.put(retval, map.get(retval)+1);
} else {
map.put(retval, 1);
}
}
for (String retval: s2.split(" ")) {
if (map.containsKey(retval)) {
map.put(retval, map.get(retval)+1);
} else {
map.put(retval, 1);
}
}
ArrayList<String> res = new ArrayList<>();
for (String str: map.keySet()) {
if (map.get(str) == 1) {
res.add(str);
}
}
return res.toArray(new String[0]);
}
}

884. 两句话中的不常见单词
https://pisces34.github.io/2022/01/30/leetcode/884/
发布于
2022年1月30日
许可协议