-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path648-Replace_Words.java
76 lines (71 loc) · 2.36 KB
/
648-Replace_Words.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
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
/* Build Trie : 字首樹
* Input: dictionary = ["cat","bat","rat"], sentence = "the cattle was rattled by the battery"
* Output: "the cat was rat by the bat"
*
* TrieTree:
* [ ]
* / | \
* b c r
* / / /
* a a a
* \ \ \
* t t t
*/
class Solution {
class TrieNode {
TrieNode[] childNode = new TrieNode[26]; //put 26 lower letter
boolean isWord = false; //if from root to this char build a word
}
public TrieNode buildTrieNode(List<String> dictionary) {
TrieNode root = new TrieNode();
TrieNode current;
for (String word : dictionary) {
current = root;
for (int i = 0; i < word.length(); i++) {
char l = word.charAt(i);
if (current.childNode[l - 'a'] == null) {
current.childNode[l - 'a'] = new TrieNode();
}
current = current.childNode[l - 'a'];
if (current.isWord) {
// exist a shorter word, we can break now
break;
}
}
current.isWord = true;
}
return root;
}
//Complexity: O(word.length())
public String findReplacedWord(TrieNode root, String word) {
TrieNode current = root;
StringBuilder result = new StringBuilder();
for (int i = 0; i < word.length(); i++) {
char l = word.charAt(i);
if (current.childNode[l - 'a'] == null) {
// Not match
result.setLength(0);
break;
};
result.append(l);
current = current.childNode[l - 'a'];
if (current.isWord) break;
}
if (result.length() == 0) {
return word;
} else {
return result.toString();
}
}
//Compexity: O(n). n = sentence.length()
public String replaceWords(List<String> dictionary, String sentence) {
TrieNode root = buildTrieNode(dictionary);
StringBuilder result = new StringBuilder();
String[] words = sentence.split(" ");
for (int i = 0; i < words.length; i++) {
result.append(findReplacedWord(root, words[i]));
result.append(" ");
}
return result.toString().trim(); // remove last space
}
}