-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathInsert-and-Search-in-a-Trie.java
49 lines (45 loc) · 1.24 KB
/
Insert-and-Search-in-a-Trie.java
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
/*
static final int ALPHABET_SIZE = 26;
// trie node
static class TrieNode {
TrieNode[] children = new TrieNode[ALPHABET_SIZE];
// isEndOfWord is true if the node represents
// end of a word
boolean isEndOfWord;
TrieNode() {
isEndOfWord = false;
for (int i = 0; i < ALPHABET_SIZE; i++) children[i] = null;
}
};
*/
//Function to insert string into TRIE.
static void insert(TrieNode root, String key)
{
// Your code here
TrieNode t = root;
for(int i=0;i<key.length();i++){
if(t.children[key.charAt(i) - 'a'] == null){
t.children[key.charAt(i) - 'a'] = new TrieNode();
}
t = t.children[key.charAt(i) - 'a'];
if(i == key.length()-1){
t.isEndOfWord = true;
}
}
}
//Function to use TRIE data structure and search the given string.
static boolean search(TrieNode root, String key)
{
// Your code here
TrieNode t = root;
for(int i=0;i<key.length();i++){
if(t.children[key.charAt(i) - 'a'] == null){
return false;
}
t = t.children[key.charAt(i) - 'a'];
if(i == key.length()-1 && t.isEndOfWord){
return true;
}
}
return false;
}