884. Uncommon words in two sentences
Title description
Given two sentences A and B. (A sentence is a series of words separated by spaces. Each word consists of lowercase letters only.)
If a word appears only once in one sentence but does not appear in the other sentence, then the word is uncommon.
Return a list of all infrequently used words.
You can return to the list in any order.
Example 1:
Input: A = "this apple is sweet", B = "this apple is sour"
Output: ["sweet","sour"]
Example 2:
Input: A = "apple apple", B = "banana"
Output: ["banana"]
Problem-solving ideas
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
//leetcode submit region begin(Prohibit modification and deletion)
class Solution_884 {
/**
* 计数法:
* 每个不常见的单词总共只出现一次。我们可以统计每个单词的出现次数,然后返回恰好出现一次的单词。
*/
public String[] uncommonFromSentences(String A, String B) {
Map<String,Integer> map = new HashMap<>();
for (String word : A.split(" ")) {
map.put(word,map.getOrDefault(word,0) + 1);
}
for (String word : B.split(" ")) {
map.put(word,map.getOrDefault(word,0) + 1);
}
List<String> ans = new LinkedList<>();
for (String word : map.keySet()) {
if (map.get(word) == 1){
ans.add(word);
}
}
return ans.toArray(new String[ans.size()]);
}
}
//leetcode submit region end(Prohibit modification and deletion)