Leetcode 884. Uncommon Words from Two Sentences
Given two sentences s1
and s2
, return a list of all the uncommon words. Uncommon words are those words that appear exactly once in one of the sentences, and do not appear in the other sentence.
HashMap
to count the frequency of each word from both sentences.Here’s how you can implement the problem in Java:
import java.util.*;
public class UncommonWords {
public static String[] uncommonFromSentences(String s1, String s2) {
// Split both sentences into words
String[] words1 = s1.split(" ");
String[] words2 = s2.split(" ");
// Use a HashMap to count the frequency of each word
Map<String, Integer> wordCount = new HashMap<>();
for (String word : words1) {
wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);
}
for (String word : words2) {
wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);
}
// List to hold the uncommon words
List<String> uncommonWords = new ArrayList<>();
for (Map.Entry<String, Integer> entry : wordCount.entrySet()) {
if (entry.getValue() == 1) {
uncommonWords.add(entry.getKey());
}
}
// Convert list to array
return uncommonWords.toArray(new String[0]);
}
public static void main(String[] args) {
// Test cases
String s1 = "this apple is sweet";
String s2 = "this apple is sour";
System.out.println(Arrays.toString(uncommonFromSentences(s1, s2))); // Output: ["sweet", "sour"]
s1 = "apple apple";
s2 = "banana";
System.out.println(Arrays.toString(uncommonFromSentences(s1, s2))); // Output: ["banana"]
}
}
s1
and s2
, respectively.s1
and s2
, respectively.s1
and s2
.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?