leetcode-884-Uncommon-Words-from-Two-Sentences

描述


We are given two sentences A and B. (A sentence is a string of space separated words. 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.

Return a list of all uncommon words.

You may return the list in any order.

Example 1:

1
2
Input: A = "this apple is sweet", B = "this apple is sour"
Output: ["sweet","sour"]

Example 2:

1
2
Input: A = "apple apple", B = "banana"
Output: ["banana"]

Note:

  1. 0 <= A.length <= 200
  2. 0 <= B.length <= 200
  3. A and B both contain only spaces and lowercase letters.

分析


用一个 Map 来存 A, B 两个数组中单词出现的次数,如果出现两次,这个单词在 A, B 两个数组都出现了,如果只出现了一次,则这个单词是题目里所要求的 uncommon word

解决方案1(Java)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public String[] uncommonFromSentences(String A, String B) {
Map<String, Integer> wordCountMap = new HashMap();
for (String word: A.split(" ")) {
wordCountMap.put(word, wordCountMap.getOrDefault(word, 0) + 1);
}
for (String word: B.split(" ")) {
wordCountMap.put(word, wordCountMap.getOrDefault(word, 0) + 1);
}

List<String> result = new LinkedList();
for (String word: wordCountMap.keySet()) {
if (wordCountMap.get(word) == 1) {
result.add(word);
}
}
return result.toArray(new String[result.size()]);
}
}

题目来源