File tree Expand file tree Collapse file tree 1 file changed +74
-0
lines changed Expand file tree Collapse file tree 1 file changed +74
-0
lines changed Original file line number Diff line number Diff line change
1
+ class WordDictionary {
2
+
3
+ Node root ;
4
+
5
+ public class Node {
6
+ char value ;
7
+ boolean isWord ;
8
+ Node [] children ;
9
+
10
+ public Node (char value ) {
11
+ this .value = value ;
12
+ isWord = false ;
13
+ children = new Node [26 ];
14
+ }
15
+ }
16
+ public WordDictionary () {
17
+ root = new Node ('\0' );
18
+ }
19
+
20
+ public void addWord (String word ) {
21
+ Node curr = root ;
22
+
23
+ for (int i = 0 ; i < word .length (); i ++) {
24
+ char ch = word .charAt (i );
25
+
26
+ if (curr .children [ch - 'a' ] == null )
27
+ curr .children [ch - 'a' ] = new Node (ch );
28
+
29
+ curr = curr .children [ch - 'a' ];
30
+
31
+ }
32
+ curr .isWord = true ;
33
+ }
34
+
35
+
36
+ // TC O(m^2)
37
+ public boolean search (String word ) {
38
+ Node curr = root ; // assigns the node that called the search function
39
+ return searchHelper (word , root );
40
+
41
+ }
42
+
43
+ public boolean searchHelper (String word , Node curr ) {
44
+
45
+ for (int i = 0 ; i < word .length (); i ++) {
46
+ char ch = word .charAt (i );
47
+
48
+ if (ch == '.' ) {
49
+ for (Node temp : curr .children ) {
50
+ if (temp != null && searchHelper (word .substring (i +1 ), temp ))
51
+ return true ;
52
+ }
53
+ return false ;
54
+ }
55
+
56
+ if (curr .children [ch - 'a' ] == null )
57
+ return false ;
58
+
59
+ curr = curr .children [ch - 'a' ];
60
+ }
61
+
62
+ if (curr .isWord == true )
63
+ return true ;
64
+ else
65
+ return false ;
66
+ }
67
+ }
68
+
69
+ /**
70
+ * Your WordDictionary object will be instantiated and called as such:
71
+ * WordDictionary obj = new WordDictionary();
72
+ * obj.addWord(word);
73
+ * boolean param_2 = obj.search(word);
74
+ */
You can’t perform that action at this time.
0 commit comments