[leetcode] problem 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

No.1

Input: A = “this apple is sweet”, B = “this apple is sour”

Output: [“sweet”,”sour”]

No.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.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public String[] uncommonFromSentences(String A, String B) {
List<String> result = new ArrayList<>();
Map<String, Integer> map = new HashMap<>();

for (String str : A.split(" "))
map.put(str, map.getOrDefault(str, 0) + 1);

for (String str : B.split(" "))
map.put(str, map.getOrDefault(str, 0) + 1);

for (Map.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue() == 1)
result.add(entry.getKey());
}

return result.toArray(new String[result.size()]);
}