1. 程式人生 > >領釦(LeetCode)兩句話中的不常見單詞 個人題解

領釦(LeetCode)兩句話中的不常見單詞 個人題解

給定兩個句子 A 和 B 。 (句子是一串由空格分隔的單詞。每個單詞僅由小寫字母組成。)

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

返回所有不常用單詞的列表。

您可以按任何順序返回列表。

 

示例 1:

輸入:A = "this apple is sweet", B = "this apple is sour"
輸出:["sweet","sour"]

示例 2:

輸入:A = "apple apple", B = "banana"
輸出:["banana"]


這個題比較簡單,把兩個字串串在一起,根據空格分離開單詞,根據題意,只出現一次的單詞就是不常見的單詞。使用一個HashMap就能快速解決問題了。

程式碼如下:

 1 class Solution {
 2     public String[] uncommonFromSentences(String A, String B) {
 3         Map<String, Integer> map=new HashMap<>();
 4         String newstr=A+" "+B;
 5         String[] getsplit=newstr.split(" ");
6 for (String string : getsplit) { 7 if(!map.containsKey(string)) 8 map.put(string, 1); 9 else 10 map.put(string, map.get(string)+1); 11 } 12 List<String> list=new ArrayList<>(); 13 14 for
(String string : map.keySet()) { 15 if(map.get(string)==1) 16 list.add(string); 17 } 18 return list.toArray(new String[list.size()]); 19 } 20 }