题目描述:
句子 是一串由空格分隔的单词。每个 单词 仅由小写字母组成。
如果某个单词在其中一个句子中恰好出现一次,在另一个句子中却 没有出现 ,那么这个单词就是 不常见的 。
给你两个 句子 s1 和 s2 ,返回所有 不常用单词 的列表。返回列表中单词可以按 任意顺序 组织。
题目思路:
两个句子中只能出现一次单词则是结果,那么可以用map统计,key为单词,value为次数,遍历map找到次数为1的单词就是答案。
代码:
package simple;
import java.util.*;
public class uncommonFromSentences {
public static String[] uncommonFromSentences(String s1, String s2) {
// 建立hashmap
HashMap<String, Integer> hashMap = new HashMap<>();
for (String s : s1.split(" ")) {
if (hashMap.containsKey(s)){
Integer integer = hashMap.get(s);
hashMap.put(s,++integer);
}else {
hashMap.put(s,1);
}
}
for (String s : s2.split(" ")) {
if (hashMap.containsKey(s)){
Integer integer = hashMap.get(s);
hashMap.put(s,++integer);
}else {
hashMap.put(s,1);
}
}
ArrayList<String> list = new ArrayList<>();
for (Map.Entry<String,Integer> entry : hashMap.entrySet()){
if (entry.getValue() == 1){
list.add(entry.getKey());
}
}
return list.toArray(new String[0]);
}
}