-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCodeSearchWordInTrie.java
More file actions
72 lines (59 loc) · 1.74 KB
/
CodeSearchWordInTrie.java
File metadata and controls
72 lines (59 loc) · 1.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// Code: Search word in Trie
// Send Feedback
// Implement the function Search for the Trie class.
// For a Trie, write the function for searching a word. Return true if the word
// is found successfully, otherwise return false.
// Note : main function is given for your reference which we are using
// internally to test the code.
import javax.swing.tree.TreeNode;
class TrieNode {
char data;
boolean isTerminating;
TrieNode children[];
int childCount;
public TrieNode(char data) {
this.data = data;
isTerminating = false;
children = new TrieNode[26];
childCount = 0;
}
}
public class Trie {
private TrieNode root;
public int count;
public Trie() {
root = new TrieNode('\0');
}
public boolean search(String word) {
return search(root, word);
}
private boolean search(TrieNode root, String word) {
// implement this function
if (word.length() == 0) {
return root.isTerminating;
}
int childIndex = word.charAt(0) - 'a';
TrieNode Child = root.children[childIndex];
if (Child == null) {
return false;
}
return search(Child, word.substring(1));
}
private void add(TrieNode root, String word) {
if (word.length() == 0) {
root.isTerminating = true;
return;
}
int childIndex = word.charAt(0) - 'a';
TrieNode child = root.children[childIndex];
if (child == null) {
child = new TrieNode(word.charAt(0));
root.children[childIndex] = child;
root.childCount++;
}
add(child, word.substring(1));
}
public void add(String word) {
add(root, word);
}
}