-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrie.java
More file actions
62 lines (56 loc) · 975 Bytes
/
Copy pathTrie.java
File metadata and controls
62 lines (56 loc) · 975 Bytes
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
import java.io.*;
import java.util.*;
import java.math.*;
class node
{
node parent;
node [] nxt;
int available;
int subt; //number of nodes in the subtrie
boolean terminal;
node ()
{
nxt = new node[26];
available = 0;
subt = 0;
terminal = false;
}
}
class Trie
{
node root;
Trie()
{
root = new node();
}
void insert(String inp)
{
node curr = root;
for(int i =0, l = inp.length(); i < l; i++)
{
if((curr.available & (1<<(inp.charAt(i)-'a'))) == 0)
{
node tmp = new node();
tmp.parent = curr;
curr.available += (1<<(inp.charAt(i)-'a'));
curr.nxt[inp.charAt(i)-'a'] = tmp;
}
curr = curr.nxt[inp.charAt(i)-'a'];
curr.subt++;
}
curr.terminal = true;
}
node search(String pref)
{
node curr = root;
for(int i = 0, l = pref.length(); i < l; i++)
{
if((curr.available & (1<<(pref.charAt(i) - 'a'))) == 0)
{
return null;
}
curr = curr.nxt[pref.charAt(i)-'a'];
}
return curr;
}
}