-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTrie.java
69 lines (58 loc) · 1.49 KB
/
Trie.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
package L208;
import java.util.HashMap;
public class Trie {
class Node {
int count;
// Node[] child;
HashMap<Character, Node> child;
Node() {
count = 0;
// child = new Node[26];
child = new HashMap<>();
}
}
Node root;
public Trie() {
root = new Node();
}
public void insert(String word) {
find(word, true, false);
}
public boolean search(String word) {
return find(word, false, false);
}
public boolean startsWith(String prefix) {
return find(prefix, false, true);
}
private boolean find(String s, boolean isInsert, boolean isPrefix) {
Node curr = root;
for (char ch : s.toCharArray()) {
/*
* 数组方式
*
* if (curr.child[ch - 'a'] == null) {
* if (isInsert)
* curr.child[ch - 'a'] = new Node();
* else
* return false;
* }
* curr = curr.child[ch - 'a'];
*/
/**
* 哈希表
*/
if (!curr.child.containsKey(ch)) {
if (isInsert)
curr.child.put(ch, new Node());
else
return false;
}
curr = curr.child.get(ch);
}
if (isInsert)
curr.count++;
if (isPrefix)
return true;
return curr.count > 0;
}
}