-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathReplaceWords.java
More file actions
123 lines (92 loc) · 3.06 KB
/
Copy pathReplaceWords.java
File metadata and controls
123 lines (92 loc) · 3.06 KB
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
/*
* https://leetcode.com/problems/replace-words/
*/
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
class TrieNode {
Map<Character, TrieNode> children = new HashMap<>();
boolean isWord;
}
class ReplaceWords {
class Trie{
TrieNode root;
public Trie() {
root = new TrieNode();
}
public String searchReplace(String word) {
TrieNode current = null;
StringBuilder sb = new StringBuilder();
Map<Character, TrieNode> children = root.children;
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
if (children.containsKey(c)) {
current = children.get(c);
sb.append(c);
if (current.isWord) {
return sb.toString();
}
} else{
if (current != null && current.isWord) {
return sb.toString();
} else {
return null;
}
}
children = current.children;
}
if (current == null) {
return null;
} else{
return sb.toString();
}
}
public void addWord(String word) {
Map<Character, TrieNode> children = root.children;
TrieNode current = null;
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
if (children.containsKey(c)) {
current = children.get(c);
} else {
current = new TrieNode();
children.put(c, current);
}
children = current.children;
if (i == word.length() -1) {
current.isWord = true;
}
}
}
}
public String replaceWords(List<String> dict, String sentence) {
//make a Trie of dictionary
Trie trie = new Trie();
Iterator<String> iter = dict.iterator();
while(iter.hasNext()) {
trie.addWord(iter.next());
}
//for each words in a sentence search if root exist
//replace if exist
//
String[] spltSentence = sentence.split("\\s+");
for (int i = 0; i < spltSentence.length; i++) {
String text = trie.searchReplace(spltSentence[i]);
if (text != null) {
spltSentence[i] = text;
}
}
return String.join(" ", spltSentence);
}
public static void main(String[] args) {
ReplaceWords obj = new ReplaceWords();
String testSentence = "the cattle was rattled by the battery";
List<String> testList = new ArrayList();
testList.add("cat");
testList.add("bat");
testList.add("rat");
System.out.println(obj.replaceWords(testList, testSentence));
}
}