884. Uncommon Words from Two Sentences

QUESTION:

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.

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"]
``````

Note:

1. `0 <= A.length <= 200`
2. `0 <= B.length <= 200`
3. `A` and `B` both contain only spaces and lowercase letters.

SOLUTION:

``````class Solution {
public String[] uncommonFromSentences(String A, String B) {
HashMap<String, Integer> mapA = uncommonFromSentencesHelper(A);
HashMap<String, Integer> mapB = uncommonFromSentencesHelper(B);
Iterator<Map.Entry<String, Integer>> iteratorA = mapA.entrySet().iterator();
String result = "";
while (iteratorA.hasNext()){
Map.Entry<String, Integer> next = iteratorA.next();
if(mapB.get(next.getKey())!=null || next.getValue()!=1) {
iteratorA.remove();
mapB.remove(next.getKey());
}else if(next.getValue()==1) {
result=result+ next.getKey()+" ";
}
}
Iterator<Map.Entry<String, Integer>> iteratorB = mapB.entrySet().iterator();
while (iteratorB.hasNext()){
Map.Entry<String, Integer> next = iteratorB.next();
if(mapA.get(next.getKey())!=null || next.getValue()!=1){
iteratorB.remove();
}else if(next.getValue()==1) {
result=result+next.getKey()+" ";
}
}
return  result.isEmpty()?new String[]{}:result.split(" ");
}
public static HashMap<String,Integer> uncommonFromSentencesHelper(String A){
HashMap<String,Integer> result = new HashMap<>();
String[] splits = A.split(" ");
for(int i = 0;i<splits.length;i++){
result.put(splits[i],result.getOrDefault(splits[i],0)+1);
}
return result;
}
}
``````
>