0884. Uncommon Words From Two Sentences

0884. Uncommon Words from Two Sentences #

题目 #

  • 句子 是一串由空格分隔的单词。每个 单词 仅由小写字母组成。
  • 如果某个单词在其中一个句子中恰好出现一次,在另一个句子中却 没有出现 ,那么这个单词就是 不常见的
  • 给你两个 句子 s1s2 ,返回所有 不常用单词 的列表。返回列表中单词可以按 任意顺序 组织。

思路 #

哈希 #

代码 #

哈希 #

class Solution {
    public String[] uncommonFromSentences(String s1, String s2) {
        String[] s1Array = s1.split(" "), s2Array = s2.split(" ");
        Map<String, Integer> s1Map = new HashMap<>(), s2Map = new HashMap<>();
        for (String str: s1Array) s1Map.put(str, s1Map.getOrDefault(str, 0) + 1);
        for (String str: s2Array) s2Map.put(str, s2Map.getOrDefault(str, 0) + 1);

        int sz = 0;
        for (String key: s1Map.keySet()) if (s1Map.get(key) == 1 && s2Map.containsKey(key) == false) sz++;
        for (String key: s2Map.keySet()) if (s2Map.get(key) == 1 && s1Map.containsKey(key) == false) sz++;

        String[] ans = new String[sz];
        int ptr = 0;
        for (String key: s1Map.keySet()) if (s1Map.get(key) == 1 && s2Map.containsKey(key) == false) ans[ptr++] = key;
        for (String key: s2Map.keySet()) if (s2Map.get(key) == 1 && s1Map.containsKey(key) == false) ans[ptr++] = key;

        return ans;
    }
}

致谢 #

宫水三叶