1
+ package joshua .leetcode .design ;
2
+
3
+ /**
4
+ * 208. Implement Trie (Prefix Tree) <br/>
5
+ * 字典树,或称前缀树 是一种快速查找前缀匹配的数据结构,例如给定一个word list,构建一个前缀树后
6
+ * 可以快速的查找某个word是否在该字典中。
7
+ * <p/>
8
+ * <a href="https://leetcode.com/problems/implement-trie-prefix-tree/">leetcode link</a>
9
+ *
10
+ * @author Joshua.Jiang on 2016/5/30.
11
+ */
12
+ public class Trie {
13
+
14
+ private TrieNode root ;
15
+
16
+
17
+ public Trie () {
18
+ root = new TrieNode ();
19
+ }
20
+
21
+ // Inserts a word into the trie.
22
+ public void insert (String word ) {
23
+ TrieNode parentNode = root ;
24
+ char [] chars = word .toCharArray ();
25
+ for (int i = 0 ; i < chars .length ; i ++) {
26
+ char ch = chars [i ];
27
+ if (parentNode .nodes [ch - 'a' ] == null ) {
28
+ parentNode .nodes [ch - 'a' ] = new TrieNode ();
29
+ if (i < chars .length -1 ) {
30
+ parentNode .nodes [ch - 'a' ].isLeafNode = false ;
31
+ }
32
+ }
33
+ if (i == chars .length - 1 ) {
34
+ parentNode .nodes [ch - 'a' ].isLeafNode = true ;
35
+ } else {
36
+ parentNode = parentNode .nodes [ch - 'a' ];
37
+ }
38
+ }
39
+ }
40
+
41
+ // Returns if the word is in the trie.
42
+ public boolean search (String word ) {
43
+ TrieNode parentNode = root ;
44
+ for (char ch : word .toCharArray ()) {
45
+ if (parentNode .nodes [ch - 'a' ] == null ) {
46
+ return false ;
47
+ }
48
+ parentNode = parentNode .nodes [ch - 'a' ];
49
+ }
50
+ return parentNode .isLeafNode ;
51
+ }
52
+
53
+ // Returns if there is any word in the trie
54
+ // that starts with the given prefix.
55
+ public boolean startsWith (String prefix ) {
56
+ TrieNode parentNode = root ;
57
+ for (char ch : prefix .toCharArray ()) {
58
+ if (parentNode .nodes [ch - 'a' ] == null ) {
59
+ return false ;
60
+ }
61
+ parentNode = parentNode .nodes [ch - 'a' ];
62
+ }
63
+ return true ;
64
+ }
65
+ }
66
+
67
+ class TrieNode {
68
+ /**
69
+ * nodes的下标表示一个字符,例如: nodes[0]不为空,表示存在字符为'a'的子节点
70
+ */
71
+ TrieNode [] nodes = new TrieNode [26 ];
72
+ boolean isLeafNode = true ;
73
+
74
+ public TrieNode () {
75
+ }
76
+ }
0 commit comments