-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrie.java
More file actions
106 lines (92 loc) · 2.43 KB
/
Trie.java
File metadata and controls
106 lines (92 loc) · 2.43 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package gfg.ds.advanced.trie;
// only works for 'a'-'z'
public class Trie {
private static final int ALPHABET_SIZE = 26;
public TrieNode root;
public Trie() {
this.root = new TrieNode(ALPHABET_SIZE);
}
public int toIndex(char ch) {
return ch - 'a';
}
// t=M; M is the key length
// s=M*n; n is no of keys in the trie
public void insert(String key) {
key = key.toLowerCase();
TrieNode curr = root;
for (char ch : key.toCharArray()) {
curr = curr.getOrCreateChild(toIndex(ch));
}
curr.isEndOfWord = true;
}
// t=M; M is the key length
public boolean search(String key) {
key = key.toLowerCase();
TrieNode curr = root;
for (char ch : key.toCharArray()) {
curr = curr.getChild(toIndex(ch));
if (curr == null) {
return false;
}
}
return curr != null && curr.isEndOfWord;
}
public boolean prefixSearch(String prefix) {
prefix = prefix.toLowerCase();
TrieNode curr = root;
for (char ch : prefix.toCharArray()) {
curr = curr.getChild(toIndex(ch));
if (curr == null) {
return false;
}
}
return curr != null;
}
// t=M; M is the key length
public void delete(String key) {
key = key.toLowerCase();
deleteUtil(key, 0, root);
}
private TrieNode deleteUtil(String key, int index, TrieNode curr) {
if (curr == null) {
return null;
}
if (index == key.length()) {
curr.isEndOfWord = false;
return curr.isEmpty() ? null : curr;
}
int childIndex = toIndex(key.charAt(index));
curr.updateChild(childIndex, deleteUtil(key, index + 1, curr.getChild(childIndex)));
if (curr.isEmpty() && !curr.isEndOfWord) {
return null;
}
return curr;
}
public static class TrieNode {
private final TrieNode[] children;
public boolean isEndOfWord;
public TrieNode(int alphabetSize) {
children = new TrieNode[alphabetSize];
}
public TrieNode getChild(int index) {
return children[index];
}
public TrieNode getOrCreateChild(int index) {
if (children[index] == null) {
children[index] = new TrieNode(children.length);
}
return children[index];
}
public void updateChild(int index, TrieNode child) {
children[index] = child;
}
public boolean isEmpty() {
for (TrieNode child : children) {
if (child != null) {
return false;
}
}
return false;
}
}
}