From e79dc0f693eac8fdafce041c1f8a940f4102028c Mon Sep 17 00:00:00 2001 From: rickben Date: Thu, 29 Oct 2020 13:49:13 +0200 Subject: [PATCH] 648 | Replace Words | Java --- Java/ReplaceWords648.java | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Java/ReplaceWords648.java diff --git a/Java/ReplaceWords648.java b/Java/ReplaceWords648.java new file mode 100644 index 00000000..8ea03d38 --- /dev/null +++ b/Java/ReplaceWords648.java @@ -0,0 +1,26 @@ +public class ReplaceWords648 { + public String replaceWords(List dictionary, String sentence) { + String result = ""; + String[] splitSentence = sentence.split(" "); + for (String word:splitSentence) { + result += " " + getRoot(word, dictionary); + } + return result.substring(1,result.length()); + } + + public String getRoot(String word, List dictionary) { + int len = word.length(); + String rootResult = ""; + for (String root:dictionary) { + if (word.length() < root.length()) + continue; + if ((word.substring(0,root.length())).equals(root) && root.length() < len){ + rootResult = root; + len = root.length(); + } + } + if (rootResult.equals("")) + return word; + return rootResult; + } +}