-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTrieEx.java
109 lines (90 loc) · 2.83 KB
/
TrieEx.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
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
package org.sean.trie;
import java.util.ArrayList;
import java.util.List;
// 211. Add and Search Word - Data structure design
public class TrieEx {
public List<TrieEx> children;
// isEndOfWord is true if the node represents end of a word
boolean isEndOfWord;
public boolean isRoot;
public Character val;
public TrieEx() {
this(true, null);
}
public TrieEx(boolean isRoot, Character t) {
this.isRoot = isRoot;
this.val = t;
children = new ArrayList<>();
}
private void insert(TrieEx node, String str, int pos) {
if (pos >= str.length()) {
node.isEndOfWord = true;
return;
}
boolean found = false;
for (TrieEx tn : node.children) {
if (tn.val.equals(str.charAt(pos))) {
found = true;
insert(tn, str, pos + 1);
break;
}
}
if (!found) {
TrieEx n = new TrieEx(false, str.charAt(pos));
node.children.add(n);
insert(n, str, pos + 1);
}
}
public void addWord(String word) {
insert(this, word, 0);
}
/***
* Retrieves the longest prefix of the given word from the trie.
*
* @param outPrefix the output {@link StringBuilder}
* @param matches the output list of matched known words
* @param word the word to retrieve the prefix from
* @param pos the current position in the word
*/
public void lookupPrefix(StringBuilder outPrefix, List<String> matches, String word, int pos) {
if (pos >= word.length()) {
return;
}
char ch = word.charAt(pos);
if (!isRoot) {
if (val == ch) {
outPrefix.append(val);
if (isEndOfWord) {
matches.add(outPrefix.toString());
}
for (TrieEx tn : children) {
tn.lookupPrefix(outPrefix, matches, word, pos + 1);
}
}
} else {
for (TrieEx tn : children) {
tn.lookupPrefix(outPrefix, matches, word, pos);
}
}
}
private boolean search(String word, int pos, boolean matchedStrictly) {
if (pos >= word.length()) {
return !matchedStrictly || isEndOfWord;
}
for (TrieEx tn : children) {
char val = tn.val;
char target = word.charAt(pos);
if (target == '.' || val == target) {
boolean found = tn.search(word, pos + 1, matchedStrictly);
if (found) return true;
}
}
return false;
}
public boolean searchPrefix(String prefix) {
return search(prefix, 0, false);
}
public boolean search(String word) {
return search(word, 0, true);
}
}