A sentence is a string of single-space separated words where 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.
Given two sentences s1
and s2
, return a list of all the uncommon words. You may return the answer in any order.
LeetCode Problem - 884
import java.util.*;
class Solution {
public String[] uncommonFromSentences(String s1, String s2) {
// Split the input sentences into arrays of words
String[] s1Arr = s1.split(" ");
String[] s2Arr = s2.split(" ");
// Calculate the total length of the combined arrays
int len = s1Arr.length + s2Arr.length;
// Merge the arrays into a single array
String[] s3Arr = new String[len];
System.arraycopy(s1Arr, 0, s3Arr, 0, s1Arr.length);
System.arraycopy(s2Arr, 0, s3Arr, s1Arr.length, s2Arr.length);
// Count the occurrences of each word using a HashMap
Map<String, Integer> mp = new HashMap<>();
for (String s : s3Arr){
mp.put(s, mp.getOrDefault(s, 0) + 1);
}
// Find words that occur only once
List<String> al = new ArrayList<>();
for (String s : s3Arr){
if (mp.get(s) == 1){
al.add(s);
}
}
// Convert the list of uncommon words to an array
String[] resultArr = new String[al.size()];
for (int i=0; i<al.size(); i++){
resultArr[i] = al.get(i);
}
// Return the array of uncommon words
return resultArr;
}
}