File tree Expand file tree Collapse file tree 1 file changed +76
-0
lines changed
solution/0208. Implement Trie (Prefix Tree) Expand file tree Collapse file tree 1 file changed +76
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Trie {
2
+
3
+ class TrieNode {
4
+
5
+ private TrieNode [] links ;
6
+
7
+ private final int R = 26 ;
8
+
9
+ private boolean isEnd ;
10
+
11
+ public TrieNode () {
12
+ links = new TrieNode [R ];
13
+ }
14
+
15
+ public boolean containsKey (char ch ) {
16
+ return links [ch -'a' ] != null ;
17
+ }
18
+
19
+ public TrieNode get (char ch ) {
20
+ return links [ch -'a' ];
21
+ }
22
+
23
+ public void put (char ch , TrieNode node ) {
24
+ links [ch -'a' ] = node ;
25
+ }
26
+
27
+ public void setEnd () {
28
+ isEnd = true ;
29
+ }
30
+
31
+ public boolean isEnd () {
32
+ return isEnd ;
33
+ }
34
+ }
35
+
36
+ private TrieNode root ;
37
+
38
+ public Trie () {
39
+ root = new TrieNode ();
40
+ }
41
+
42
+ public void insert (String word ) {
43
+ TrieNode node = root ;
44
+ for (int i = 0 ; i < word .length (); i ++) {
45
+ char currentChar = word .charAt (i );
46
+ if (!node .containsKey (currentChar )) {
47
+ node .put (currentChar , new TrieNode ());
48
+ }
49
+ node = node .get (currentChar );
50
+ }
51
+ node .setEnd ();
52
+ }
53
+
54
+ private TrieNode searchPrefix (String word ) {
55
+ TrieNode node = root ;
56
+ for (int i = 0 ; i < word .length (); i ++) {
57
+ char curLetter = word .charAt (i );
58
+ if (node .containsKey (curLetter )) {
59
+ node = node .get (curLetter );
60
+ } else {
61
+ return null ;
62
+ }
63
+ }
64
+ return node ;
65
+ }
66
+
67
+ public boolean search (String word ) {
68
+ TrieNode node = searchPrefix (word );
69
+ return node != null && node .isEnd ();
70
+ }
71
+
72
+ public boolean startsWith (String prefix ) {
73
+ TrieNode node = searchPrefix (prefix );
74
+ return node != null ;
75
+ }
76
+ }
You can’t perform that action at this time.
0 commit comments