Uncommon Words from Two Sentences LT884

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:

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

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

 Idea 1. HashMap count the occurences, find the occurence == 1, 读题啊,一开始还写了2个map

Time complexity: O(M + N), M = A.length(), N = B.length()

Space complexity: O(M + N)

 1 class Solution {
 2     public String[] uncommonFromSentences(String A, String B) {
 3         Map<String, Integer> count = new HashMap<>();
 4         for(String str: A.split("\\s")) {
 5             count.put(str, count.getOrDefault(str, 0) + 1);
 6         }
 7         
 8         for(String str: B.split("\\s")) {
 9             count.put(str, count.getOrDefault(str, 0) + 1);
10         }
11         
12         List<String> result = new ArrayList<>();
13         for(String str: count.keySet()) {
14             if(count.get(str) == 1) {
15                 result.add(str);
16             }
17         }
18         
19         return result.stream().toArray(String[]::new);
20     }
21 }

猜你喜欢

转载自www.cnblogs.com/taste-it-own-it-love-it/p/10681013.html