884.两句话中的不常见单词
题目描述
思路
模拟
根据题意,某个单词在一边出现一次,另外一边不曾出现,相当于某个单词总共只出现一次。
所以可以把两个句子拼接进行词频统计,只出现一次的都是不常见单词,返回即可。
Python实现
class Solution:
def uncommonFromSentences(self, s1: str, s2: str) -> List[str]:
s = s1 + " " + s2
lst = s.split()
counter = Counter(lst)
ans = []
for each in counter.items():
(key, value) = each
if value == 1:
ans.append(key)
return ans
Java实现
class Solution {
public String[] uncommonFromSentences(String s1, String s2) {
String s = s1 + " " + s2;
Map<String, Integer> map = new HashMap<>();
String[] words = s.split(" ");
for (String word: words) {
map.put(word, map.getOrDefault(word, 0) + 1);
}
List<String> list = new ArrayList<>();
for (String word: map.keySet()) {
if (map.get(word) == 1) {
list.add(word);
}
}
return list.toArray(new String[list.size()]);
}
}