-
Notifications
You must be signed in to change notification settings - Fork 354
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #833 from rickben/replace-words-648
648 | Replace Words | Java
- Loading branch information
Showing
1 changed file
with
26 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} |