1
+ public class tireExample {
2
+ public static void main (String [] args ) {
3
+ String words [] = {"hello" , "world" , "hi" , "her" , "hero" };
4
+
5
+ // Insert all words into the trie
6
+ for (String word : words ) {
7
+ insert (word );
8
+ }
9
+
10
+ // Test search functionality
11
+ System .out .println ("Search 'hello': " + search ("hello" ));
12
+ System .out .println ("Search 'he': " + search ("he" ));
13
+ System .out .println ("Search 'her': " + search ("her" ));
14
+ System .out .println ("Search 'xyz': " + search ("xyz" ));
15
+
16
+ // Test prefix functionality
17
+ System .out .println ("Has prefix 'he': " + startsWith ("he" ));
18
+ System .out .println ("Has prefix 'wor': " + startsWith ("wor" ));
19
+ System .out .println ("Has prefix 'xyz': " + startsWith ("xyz" ));
20
+ }
21
+
22
+ // node class ->
23
+ static class Node {
24
+ Node children [];
25
+ boolean eow ; // end of word
26
+
27
+ // constructor of Node
28
+ public Node () {
29
+ children = new Node [26 ];
30
+ for (int i = 0 ; i < 26 ; i ++) {
31
+ children [i ] = null ;
32
+ }
33
+ eow = false ;
34
+ }
35
+ }
36
+
37
+ // node root ->
38
+ static Node root = new Node ();
39
+
40
+ // insert operation
41
+ public static void insert (String word ) {
42
+ Node current = root ; // Use a current pointer instead of modifying root
43
+
44
+ for (int i = 0 ; i < word .length (); i ++) {
45
+ int index = word .charAt (i ) - 'a' ;
46
+
47
+ if (current .children [index ] == null ) {
48
+ current .children [index ] = new Node (); // create a new node
49
+ }
50
+
51
+ current = current .children [index ]; // move to next node
52
+ }
53
+
54
+ // Mark end of word after the loop
55
+ current .eow = true ;
56
+ }
57
+
58
+ // search operation
59
+ public static boolean search (String word ) {
60
+ Node current = root ;
61
+
62
+ for (int i = 0 ; i < word .length (); i ++) {
63
+ int index = word .charAt (i ) - 'a' ;
64
+
65
+ if (current .children [index ] == null ) {
66
+ return false ;
67
+ }
68
+
69
+ current = current .children [index ];
70
+ }
71
+
72
+ return current .eow ; // return true only if it's end of a word
73
+ }
74
+
75
+ // check if any word starts with given prefix
76
+ public static boolean startsWith (String prefix ) {
77
+ Node current = root ;
78
+
79
+ for (int i = 0 ; i < prefix .length (); i ++) {
80
+ int index = prefix .charAt (i ) - 'a' ;
81
+
82
+ if (current .children [index ] == null ) {
83
+ return false ;
84
+ }
85
+
86
+ current = current .children [index ];
87
+ }
88
+
89
+ return true ; // prefix exists
90
+ }
91
+ }
0 commit comments