We are given two sentencesA
andB
. (Asentence is a string of space separated words. Each_word_consists only of lowercase letters.)
A word isuncommon 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.
Note:
0 <= A.length <= 200
0 <= B.length <= 200
A
andB
both contain only spaces and lowercase letters.
这道题也没啥意思,按照要求来
class Solution {
public String[] uncommonFromSentences(String A, String B) {
HashMap<String, Boolean> mapA = new HashMap<>();
HashMap<String, Boolean> mapB = new HashMap<>();
List<String> list = new ArrayList<String>();
int i = 0;
while(i < A.length()) {
while(i < A.length() && A.charAt(i) == ' ')
i++;
int j = i;
while(j < A.length() && A.charAt(j) != ' ')
j++;
String word = A.substring(i, j);
if(mapA.containsKey(word))
mapA.put(word, false);
else
mapA.put(word, true);
i = j;
}
i = 0;
while(i < B.length()) {
while(i < B.length() && B.charAt(i) == ' ')
i++;
int j = i;
while(j < B.length() && B.charAt(j) != ' ')
j++;
String word = B.substring(i, j);
if(mapB.containsKey(word))
mapB.put(word, false);
else
mapB.put(word, true);
i = j;
}
for(Map.Entry<String, Boolean> entry: mapA.entrySet()) {
if(!entry.getValue())
continue;
if(!mapB.containsKey(entry.getKey()))
list.add(entry.getKey());
}
for(Map.Entry<String, Boolean> entry: mapB.entrySet()) {
if(!entry.getValue())
continue;
if(!mapA.containsKey(entry.getKey()))
list.add(entry.getKey());
}
String[] res = new String[list.size()];
for(i = 0; i < res.length; i++)
res[i] = list.get(i);
return res;
}
}