Tries

REF. geeksforgeeks

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
73
74
class TrieNode {
TrieNode[] children = new TrieNode[26];
boolean isEndOfWord; // isEndOfWord is true if the node represents end of a word
}

class Trie {
static TrieNode root=new TrieNode();
// If not present, inserts key into trie
// If the key is prefix of trie node,
// just marks leaf node
static void insert(String key) {
int length = key.length();
TrieNode p = root;

for (int level = 0; level < length; level++) {
int index = key.charAt(level) - 'a';
if (p.children[index] == null){
p.children[index] = new TrieNode();
}
p = p.children[index];
}
// mark last node as leaf
p.isEndOfWord = true;
}

// Returns true if key presents in trie, else false
static boolean search(String key) {
int length = key.length();
TrieNode p = root;

for (int level = 0; level < length; level++) {
int index = key.charAt(level) - 'a';

if (p.children[index] == null){
return false;
}

p = p.children[index];
}
// if reach the key end and the node is the end of the word, return true.
return (p != null && p.isEndOfWord);
}
}

public class MyClass { // Driver
public static void main(String args[]) {
// Input keys (use only 'a' through 'z' and lower case)
String keys[] = { "the", "a", "there", "answer", "any", "by", "bye", "their" };
String output[] = { "Not present in trie", "Present in trie" };
// Construct trie
for (int i = 0; i < keys.length; i++)
Trie.insert(keys[i]);

// Search for different keys
if (Trie.search("the") == true)
System.out.println("the --- " + output[1]);
else
System.out.println("the --- " + output[0]);

if (Trie.search("these") == true)
System.out.println("these --- " + output[1]);
else
System.out.println("these --- " + output[0]);
if (Trie.search("their") == true)
System.out.println("their --- " + output[1]);
else
System.out.println("their --- " + output[0]);

if (Trie.search("thaw") == true)
System.out.println("thaw --- " + output[1]);
else
System.out.println("thaw --- " + output[0]);
}
}


0%