[LeetCode] 884. Uncommon Words from Two Sentences

CNoodle發表於2024-09-18

A sentence is a string of single-space separated words where 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.

Given two sentences s1 and s2, return a list of all the uncommon words. You may return the answer in any order.

Example 1:
Input: s1 = "this apple is sweet", s2 = "this apple is sour"
Output: ["sweet","sour"]

Explanation:
The word "sweet" appears only in s1, while the word "sour" appears only in s2.

Example 2:
Input: s1 = "apple apple", s2 = "banana"
Output: ["banana"]

Constraints:
1 <= s1.length, s2.length <= 200
s1 and s2 consist of lowercase English letters and spaces.
s1 and s2 do not have leading or trailing spaces.
All the words in s1 and s2 are separated by a single space.

兩句話中的不常見單詞。

句子 是一串由空格分隔的單詞。每個 單詞 僅由小寫字母組成。

如果某個單詞在其中一個句子中恰好出現一次,在另一個句子中卻 沒有出現 ,那麼這個單詞就是 不常見的 。

給你兩個 句子 s1 和 s2 ,返回所有 不常用單詞 的列表。返回列表中單詞可以按 任意順序 組織。

思路

題意是讓我們找某些單詞,這些單詞需要在其中一個句子中恰好出現一次,在另一個句子中卻沒有出現。這個條件等同於這些要找的單詞在全域性只出現一次

我們可以用一個HashMap來統計每個單詞出現的次數,然後遍歷兩個句子,統計每個單詞出現的次數,如果出現次數為1,則加入到結果集中。

複雜度

時間O(n)
空間O(n)

程式碼

Java實現

class Solution {
    public String[] uncommonFromSentences(String s1, String s2) {
        HashMap<String, Integer> map = new HashMap<>();
        for (String word : s1.split(" ")) {
            map.put(word, map.getOrDefault(word, 0) + 1);
        }

        for (String word : s2.split(" ")) {
            map.put(word, map.getOrDefault(word, 0) + 1);
        }

        List<String> list = new ArrayList<>();
        for (String word : s1.split(" ")) {
            if (map.get(word) == 1) {
                list.add(word);
            }
        }
        for (String word : s2.split(" ")) {
            if (map.get(word) == 1) {
                list.add(word);
            }
        }

        int n = list.size();
        String[] res = list.toArray(new String[n]);
        return res;
    }
}

相關文章