2024-09-17|閱讀時間 ‧ 約 5 分鐘

【LeetCode】884. Uncommon Words from Two Sentences

題目敘述

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;
}
}
分享至
成為作者繼續創作的動力吧!
© 2024 vocus All rights reserved.