File tree Expand file tree Collapse file tree 1 file changed +69
-0
lines changed Expand file tree Collapse file tree 1 file changed +69
-0
lines changed Original file line number Diff line number Diff line change 1+ package tries ;
2+
3+ // dictionary;
4+ // add,search and remove
5+
6+
7+ // here if we use hashmap then complexity is O(1) in avg case. and it is independent of
8+ // entries in the hashmap..
9+ // in hashmap we calculate hashcode for this takes time equal to word length for every opn.
10+ class TrieNode {
11+
12+ char data ;
13+ boolean isTerminating ;
14+ TrieNode children [];
15+
16+ public TrieNode (char data ) {
17+
18+ this .data = data ;
19+ isTerminating = false ;
20+ children = new TrieNode [26 ];
21+
22+ }
23+
24+
25+ }
26+
27+
28+ public class impl {
29+
30+ TrieNode root ;
31+
32+ public impl () {
33+
34+ root = new TrieNode ('\0' );
35+ }
36+
37+
38+ private void add (TrieNode root , String word ) {
39+
40+
41+ if (word .length () == 0 ) {
42+
43+ root .isTerminating = true ;
44+ return ;
45+ }
46+
47+
48+ int childIndex = word .charAt (0 ) - 'a' ;
49+ TrieNode child = root .children [childIndex ];
50+ if (child == null ) {
51+ child = new TrieNode (word .charAt (0 ));
52+ root .children [childIndex ] = child ;
53+ }
54+
55+ add (child , word .substring (1 ));
56+
57+ }
58+
59+
60+
61+ public void add (String word ) {
62+ add (root , word );
63+
64+
65+ }
66+
67+
68+
69+ }
You can’t perform that action at this time.
0 commit comments