-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathTrie.java
More file actions
54 lines (49 loc) · 1.31 KB
/
Trie.java
File metadata and controls
54 lines (49 loc) · 1.31 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
class TrieNode{
TrieNode[] children = new TrieNode[26];
boolean isWordEnd;
}
public class Trie {
public TrieNode root;
public Trie(){
root = new TrieNode();
//这里还是要注意一下
root.isWordEnd = true;
}
// search word
public boolean search(String word){
TrieNode cur = root;
for(char c : word.toCharArray()){
TrieNode next = cur.children[c-'a'];
if(next == null) return false;
cur = next;
}
// 注意不要直接返回true
return cur.isWordEnd;
}
// insert a word
public void insert(String word){
TrieNode cur = root;
for(char c : word.toCharArray()){
TrieNode next = cur.children[c-'a'];
if(next == null){
next = new TrieNode();
cur.children[c-'a'] = next;
}
cur = next;
}
// 别忘了把isWordEnd变成true
cur.isWordEnd = true;
}
// search prefix
public boolean startsWith(String prefix){
TrieNode cur = root;
for(char c : prefix.toCharArray()){
TrieNode next = cur.children[c-'a'];
if(next == null){
return false;
}
cur = next;
}
return true;
}
}