From bcb4538b17fa6d4e84db0462a5c369d84add1c52 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Fri, 7 Jun 2024 19:38:59 +0200 Subject: [PATCH] =?UTF-8?q?java:=20add=20=C2=AB648.=20Replace=20Words?= =?UTF-8?q?=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- java/replace-words.java | 78 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 java/replace-words.java diff --git a/java/replace-words.java b/java/replace-words.java new file mode 100644 index 0000000..e8bf7b3 --- /dev/null +++ b/java/replace-words.java @@ -0,0 +1,78 @@ +import java.util.List; + +class Solution { + private class Trie { + public Trie() { + root = new TrieNode(); + } + + public void insert(String word) { + root.insert(word); + } + + public String shortestPrefix(String word) { + return root.shortestPrefix(word); + } + + private TrieNode root; + + private class TrieNode { + boolean has; + TrieNode[] successors; + + TrieNode() { + has = false; + successors = new TrieNode[26]; + } + + void insert(String word) { + TrieNode node = this; + + for (int i = 0; i < word.length(); ++i) { + int idx = word.charAt(i) - 'a'; + + if (node.successors[idx] == null) { + node.successors[idx] = new TrieNode(); + } + node = node.successors[idx]; + } + + node.has = true; + } + + String shortestPrefix(String word) { + TrieNode node = this; + + for (int i = 0; i < word.length(); ++i) { + int idx = word.charAt(i) - 'a'; + + if (node.successors[idx] == null) { + return word; + } + + node = node.successors[idx]; + if (node.has) { + return word.substring(0, i + 1); + } + } + + return word; + } + } + } + + public String replaceWords(List dictionary, String sentence) { + String words[] = sentence.split(" "); + + var t = new Trie(); + for (var word : dictionary) { + t.insert(word); + } + + for (int i = 0; i < words.length; ++i) { + words[i] = t.shortestPrefix(words[i]); + } + + return String.join(" ", words); + } +}