-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathTrie.java
More file actions
50 lines (43 loc) · 1.46 KB
/
Trie.java
File metadata and controls
50 lines (43 loc) · 1.46 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
class Trie {
static node root = new node(-1);
static int[] ord = new int[26];
static void main(String[] args){
for(int i = 0; i < 26; i++) ord[i] = i;
}
static class node{
char l;
boolean term = false;
int numWords = 0;
node[] children = new node[26];
node(int lIn){
l = (char) (lIn + 'a');
}
void push(int[] word, int idx){
numWords++;
if(idx == word.length){
term = true;
return;
}
if(children[word[idx]] == null) children[word[idx]] = new node(word[idx]);
children[word[idx]].push(word, idx + 1);
}
int getNumWords(int[] word, int idx){
if(idx == word.length) return numWords;
if(children[word[idx]] == null) return 0;
return children[word[idx]].getNumWords(word, idx + 1);
}
String getNthString(int in){
if(in == 1 && term) return "";
int numSeen = term ? 1 : 0;
for(int i : ord){
if(children[i] == null) continue;
node next = children[i];
if(numSeen + next.numWords >= in){
return next.l + next.getNthString(in - numSeen);
}
numSeen += next.numWords;
}
return "";
}
}
}