【LeetCode】884. Uncommon Words from Two Sentences
avatar-img
Err500

【LeetCode】884. Uncommon Words from Two Sentences

揚-avatar-img
發佈於Leetcode
更新於 發佈於 閱讀時間約 5 分鐘

題目敘述

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.


  1. 句子(sentence)的定義:小寫字母拼成的單字所組成的字串,每個單字間由單一個空白字元進行分隔。
  2. uncommon的定義:在單一句子內只出現一次,並且沒有出現在另外一句中。
  3. 給兩個句子s1s2,回傳所有符合uncommon定義的單字,可以為任意順序。


範例

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.
  • 單一句子內不超過200個字元
  • 單一句子由小寫英文字母及空白所組成
  • 單一句子的首尾沒有空白
  • 所有句子中的單字都由空白分隔


思考方向

  1. 有去重複的特性,考慮用SetHashMap
  2. 句子的結構定義是一樣的,可以串在一起後,用迴圈一次處理。
  3. 考慮兩句都有出現,但在個別句子都只出現一次的案例,在組合後的單一句子中會出現重複的單字,需另外進行排除,例如Example 1中的this、apple、is
  4. 回傳結果的型別轉換處理,以符合題目要求的字串陣列。


解法

class Solution {
public String[] uncommonFromSentences(String s1, String s2) {
Set<String> set = new HashSet<>();
Set<String> duplicate = new HashSet<>();
String all = String.join(" ", s1, s2);

for (String word : all.split(" ")) {
if (set.contains(word)) {
duplicate.add(word);
continue;
}
set.add(word);
}

for (String word : duplicate) {
set.remove(word);
}

String[] result = set.toArray(new String[0]);
return result;
}
}
avatar-img
Err500
12會員
76內容數
遇到的坑、解過的題、新知識的探索、舊時代的遺毒!? 工作後我發現,文件更新往往跟不上新需求的更迭,犯錯的歷史總是不斷重演。因此,我改變了方式,蒐集從程式上、系統上的每一次異常處理過程,好讓再次遇到相同的問題時能快速應變。此專題就是我的錯題本,期待日後不管在工作上或交流上遇到難題,都能輕鬆地應答:有什麼難的,我都踩過。
留言
avatar-img
留言分享你的想法!
Err500 的其他內容
題目 Given two integer arrays pushed and popped each with distinct values, return true if this could have been the result of a sequence of push and pop
題目 Given two integer arrays pushed and popped each with distinct values, return true if this could have been the result of a sequence of push and pop