From 12f5d72bf290deb2c282429a8bcdf6454fe9fafe Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Tue, 17 Sep 2024 18:13:29 +0200 Subject: [PATCH] =?UTF-8?q?java:=20add=20=C2=AB884.=20Uncommon=20Words=20f?= =?UTF-8?q?rom=20Two=20Sentences=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- java/uncommon-words-from-two-sentences.java | 27 +++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 java/uncommon-words-from-two-sentences.java diff --git a/java/uncommon-words-from-two-sentences.java b/java/uncommon-words-from-two-sentences.java new file mode 100644 index 0000000..a79b54f --- /dev/null +++ b/java/uncommon-words-from-two-sentences.java @@ -0,0 +1,27 @@ +import java.util.ArrayList; +import java.util.HashMap; + +class Solution { + public String[] uncommonFromSentences(String s1, String s2) { + var counters = new HashMap(); + + for (String word : s1.strip().split("\\s+")) { + counters.compute(word, (key, count) -> 1 + (count != null ? count : 0)); + } + + for (String word : s2.strip().split("\\s+")) { + counters.compute(word, (key, count) -> 1 + (count != null ? count : 0)); + } + + var uncommon = new ArrayList(); + for (var entry : counters.entrySet()) { + if (entry.getValue() != 1) { + continue; + } + + uncommon.add(entry.getKey()); + } + + return uncommon.toArray(new String[0]); + } +}