Skip to content

Commit

Permalink
648 | Replace Words | Java
Browse files Browse the repository at this point in the history
  • Loading branch information
rickben committed Oct 29, 2020
1 parent fa345d8 commit e79dc0f
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions Java/ReplaceWords648.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
public class ReplaceWords648 {
public String replaceWords(List<String> 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<String> 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;
}
}

0 comments on commit e79dc0f

Please sign in to comment.