问题描述:
We are given two sentences s1 and s2. (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.
找出s1中只出现一次且在s2中未出现过的单词,反之亦然
思路:
这道题的英文表达有点误导人,不是uncommon word 而是 unique word
这样我们把两个字符串合并(用空格隔开),再用一个哈希表记录单词以及出现的次数。
我的方法有点绕,用了两个哈希表,两个数组
代码如下:
class Solution {
Map<String,Integer> map1=new HashMap<>();
Map<String,Integer> map2=new HashMap<>();
public String[] uncommonFromSentences(String s1, String s2) {
s1=s1+" ";
s2=s2+" ";
addWordsToMap(s1, map1);
addWordsToMap(s2, map2);
List<String> list=new ArrayList<>();
for(String a: map1.keySet()){
if((map1.get(a)==1)&&(!map2.containsKey(a))){
list.add(a);
}
}
for(String a: map2.keySet()){
if((map2.get(a)==1)&&(!map1.containsKey(a))){
list.add(a);
}
}
String[] ans=new String[list.size()];
for(int i=0; i<list.size(); i++){
ans[i]=list.get(i);
}
return ans;
}
private void addWordsToMap(String s, Map x){
int slower=0;
for(int faster=1; faster<s.length(); faster++){
if((s.charAt(faster)==' ')&&(s.charAt(faster-1)!=' ')){
String nextWord=s.substring(slower,faster);
if(!x.containsKey(nextWord)){
x.put(nextWord,1);
}
else{
x.put(nextWord,2);
}
}
if((s.charAt(faster)!=' ')&&(s.charAt(faster-1)==' ')){
slower=faster;
}
}
}
}
时间复杂度: O(m+n)