Input: s1 ="this apple is sweet", s2 ="this apple is sour"Output: ["sweet","sour"]Explanation:
The word "sweet" appears only in s1,while the word "sour" appears only in s2.
publicclassSolution {
public String[]uncommonFromSentences(String s1, String s2) {
// Combine both sentences into one String combined = s1 +" "+ s2;
// Use a HashMap to count the occurrences of each word HashMap<String, Integer> count =new HashMap<>();
for (String word : combined.split(" ")) {
count.put(word, count.getOrDefault(word, 0) + 1);
}
// Gather all words that appear exactly once List<String> ans =new ArrayList<>();
for (Map.Entry<String, Integer> entry : count.entrySet()) {
if (entry.getValue() == 1) {
ans.add(entry.getKey());
}
}
return ans.toArray(new String[0]);
}
}
1
2
3
4
5
6
7
8
9
10
classSolution:
defuncommonFromSentences(self, s1: str, s2: str) -> List[str]:
# Combine both sentences into one combined = s1 +" "+ s2
# Use a Counter to count the occurrences of each word count = Counter(combined.split())
# Gather all words that appear exactly oncereturn [word for word, freq in count.items() if freq ==1]