-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathReplaceWords.java
37 lines (31 loc) · 1.06 KB
/
ReplaceWords.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package com.smlnskgmail.jaman.leetcodejava.medium;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
// https://leetcode.com/problems/replace-words/
public class ReplaceWords {
private final List<String> dictionary;
private final String sentence;
public ReplaceWords(List<String> dictionary, String sentence) {
this.dictionary = dictionary;
this.sentence = sentence;
}
public String solution() {
Set<String> roots = new HashSet<>(dictionary);
String[] words = sentence.split(" ");
StringBuilder result = new StringBuilder();
for (String word : words) {
String insertWord = word;
for (int i = 1; i <= word.length(); i++) {
String sub = word.substring(0, i);
if (roots.contains(sub)) {
insertWord = sub;
break;
}
}
result.append(insertWord).append(" ");
}
result.deleteCharAt(result.length() - 1);
return result.toString();
}
}