Uncommon Words from Two Sentences

https://leetcode.com/problems/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:

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.

解题思路:

简单但是蛋疼的一道题目。读题目后发现,这里的uncommon,其实就是在A和B里面加起来只出现一次的。

先用map统计次数,然后拿出只出现一次的词,最后形成array。

class Solution {
    public String[] uncommonFromSentences(String A, String B) {
        Map<String, Integer> map = new HashMap<String, Integer>();
        String[] a1 = A.split(" ");
        String[] b1 = B.split(" ");
        for (String str : a1) {
            map.put(str, map.getOrDefault(str, 0) + 1);
        }
        for (String str : b1) {
            map.put(str, map.getOrDefault(str, 0) + 1);
        }
        
        List<String> list = new ArrayList<String>();
        for (Map.Entry<String, Integer> entry : map.entrySet())
        {
            if (entry.getValue() == 1) {
                list.add(entry.getKey());
            }
        }
        String[] res = new String[list.size()];
        for (int i = 0; i < list.size(); i++) {
            res[i] = list.get(i);
        }
        return res;
    }
}

有人写的更简洁,逻辑是一样的

https://leetcode.com/problems/uncommon-words-from-two-sentences/discuss/158967/C%2B%2BJavaPython-Easy-Solution-with-Explanation

猜你喜欢

转载自www.cnblogs.com/NickyYe/p/9972739.html