884-两句话中的不常见单词

前言

LeetCode Weekly Contest 97的第一道题目,分值为3分。原题目要求如下:

给定两个句子 A 和 B 。 (句子是一串由空格分隔的单词。每个单词仅由小写字母组成。)

如果一个单词在其中一个句子中只出现一次,在另一个句子中却没有出现,那么这个单词就是不常见的。

返回所有不常用单词的列表。

您可以按任何顺序返回列表。

示例 1:

输入:A = "this apple is sweet", B = "this apple is sour"
输出:["sweet","sour"]
示例 2:

输入:A = "apple apple", B = "banana"
输出:["banana"]

提示:
0 <= A.length <= 200
0 <= B.length <= 200
A 和 B 都只包含空格和小写字母。

解题思路

这个题目其实很简单,解题步骤如下:
1.先统计每个单词的出现次数,生成以单词和出现次数为元素的集合
2.获取两个集合不相交且集合元素中出现次数为1的元素

以示例1为例子:

  1. 获取到的元素如下:
集合A
[{"this",1},{"apple",1},{"is",1},{"sweet",1}]
集合B
[{"this",1},{"apple",1},{"is",1},{"sour",1}]

2.我取不相交的部分的思路是先取出相交的部分集合C,然后分别取出集合A和集合B中集合C且出现次数不为1的元素:

集合C
[{"this",1},{"apple",1},{"is",1}]

结果集合
[{"sweet",1},{"sour",1}]

最后取出结果集合中的单词即可
["sweet","sour"]

实现代码

    public String[] uncommonFromSentences(String A, String B) {
        Map mapA = getCountMap(A);
        Map mapB = getCountMap(B);
        Set set = new HashSet<>();
        Set sameSet = new HashSet<>();
        //两个集合中都出现的单词
        for (String keyA : mapA.keySet()) {
            for (String keyB : mapB.keySet()) {
                if (keyA.equals(keyB)) {
                    sameSet.add(keyA);
                }
            }
        }
        calDiff(mapA, sameSet, set);
        calDiff(mapB, sameSet, set);
        return set.toArray(new String[set.size()]);
    }

    /**
     * 返回句子中每个单词的出现次数统计情况,key为单词,value为出现次数
     * @param str
     * @return
     */
    private Map getCountMap(String str) {
        Map map = new HashMap<>();
        if (str != null && str.length() > 0) {
            String[] strs = str.split(" ");
            for (String s : strs) {
                if (map.containsKey(s)) {
                    map.put(s, map.get(s) + 1);
                } else {
                    map.put(s, 1);
                }
            }
        }
        return map;
    }

    /**
     * 取出Map中不存在重复集合中的key,且key的value不为1
     * @param map
     * @param sameSet 重复集合
     * @param set
     */
    private void calDiff(Map map, Set sameSet, Set set) {
        if (!map.isEmpty()) {
            Iterator> it = map.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry entry = it.next();
                String key = entry.getKey();
                if (!sameSet.contains(key) && entry.getValue() == 1) {
                    set.add(key);
                }
            }
        }
    }

你可能感兴趣的:(leetcode,算法,java)