884. 两句话中的不常见单词『简单』

题目来源于力扣(LeetCode

一、题目

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

题目相关标签:哈希表

提示:

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

二、解题思路

  1. 定义 Map,并通过字符串的 split() 方法,对字符串 A 与 B 中的进行空格的分隔

  2. 遍历两个字符串数组,将字符串与字符串出现的次数添加到 Map 中

  3. 遍历 Map,对字符串(键)出现次数(值)等于 1 的字符串元素添加到 list 结果中

三、代码实现

public static String[] uncommonFromSentences(String A, String B) {
    Map<String, Integer> map = new HashMap<>();
    List<String> list = new ArrayList<>();

    String[] strsA = A.split(" ");
    String[] strsB = B.split(" ");

    for (String str : strsA) {
        map.put(str, map.getOrDefault(str, 0) + 1);
    }
    for (String str : strsB) {
        map.put(str, map.getOrDefault(str, 0) + 1);
    }

    Set<String> strs = map.keySet();
    for (String str : strs) {
        // 将单词出现次数等于 1 的字符串加入结果集中
        if (map.get(str) < 2) {
            list.add(str);
        }
    }

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

四、执行用时

五、部分测试用例

public static void main(String[] args) {
    String A = "this apple is sweet", B = "this apple is sour";  
    // output: "sweet","sour"
//    String A = "apple apple", B = "banana";  // output: "banana"

    String[] result = uncommonFromSentences(A, B);
    System.out.println(Arrays.toString(result));
}
posted @ 2020-07-01 21:41  知音12138  阅读(152)  评论(0编辑  收藏  举报