LeetCode-Uncommon Words from Two Sentences

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24133491/article/details/82732310

Description:
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:

  • 0 <= A.length <= 200
  • 0 <= B.length <= 200
  • A and B both contain only spaces and lowercase letters.

题意:给定两个字符串,字符串中包含用空格分隔开的单词;要求找出所有在两个串中只出现过一次的单词;

解法:我们可以将两个串中的单词及其出现的次数作为键值对存储在哈希表中,这样遍历哈希表返回只出现一次的键;

Java
class Solution {
    public String[] uncommonFromSentences(String A, String B) {
        StringBuilder result = new StringBuilder();
        Map<String, Integer> words = new HashMap<>();
        getWords(words, A);
        getWords(words, B);
        for (String word : words.keySet()) {
            if (words.get(word) == 1) {
                result.append(word + "\u0020");
            }
        }
        return result.length() == 0 ? new String[] {} : result.toString().split("\u0020");
    }

    private void getWords(Map<String, Integer> words, String s) {
        for (String word : s.split("\u0020")) {
            words.put(word, words.getOrDefault(word, 0) + 1);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_24133491/article/details/82732310