Leetcode学习笔记:#884. Uncommon Words from Two Sentences
We are given two sentences A and B. (A sentence is a string of space separated words. 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.
Return a list of all uncommon words.
You may return the list in any order.
实现:
public String[] uncommonFromSentences(String A, String B){
Map<String, Integer> count = new HashMap<>();
for(String w : (A + " " + B).split(" "))
count.put(w, count.getOrDefault(w, 0) + 1);
ArrayList<String> res = new ArrayList<>();
for(String w : count.keySet())
if(count.get(w) == 1)
res.add(w);
return res.toArray(new String[0]);
}
思路:
map记录每个单词出现的次数,再遍历map看哪个单词出现次数为1。