-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrie.js
86 lines (75 loc) · 1.97 KB
/
trie.js
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
class Node {
constructor() {
this.child = new Array(26) ;
this.pref = 0;
this.end = 0;
this.links = [] ;
}
exist = (ch) => {
ch = ch.toLowerCase();
const num = ch.charCodeAt(0) - 97 ;
return this.child[ num ] != undefined ;
}
push = (ch) => {
ch = ch.toLowerCase();
const num = ch.charCodeAt(0) - 97 ;
this.child[ num ] = new Node() ;
}
get = (ch) => {
ch = ch.toLowerCase();
const num = ch.charCodeAt(0) - 97 ;
return this.child[num] ;
}
}
class Trie {
root = new Node() ;
insertWord = (str , link) => {
let node = this.root;
for (let i=0; i<str.length; i++){
const ch = str[i].toLowerCase() ;
if (node.exist(ch) ){
node = node.get(ch) ;
}
else {
node.push(ch) ;
node = node.get(ch) ;
node.pref++;
}
}
node.end++;
node.links.push(link);
}
getWordsUtil = (node , ans , arr) => {
if (node.end>0){
ans.push({str: arr.join("") , links : node.links}) ;
}
for (let i=97; i<=122; i++){
const ch = String.fromCharCode(i) ;
if (node.exist(ch)){
arr.push(ch) ;
this.getWordsUtil(node.get(ch) , ans , arr) ;
arr.pop() ;
}
}
}
getWords = (str) => {
if (str.length == 0)
return [] ;
const ans = [] ;
const arr = [] ;
let node = this.root;
for (let i=0; i<str.length; i++){
const ch = str[i].toLowerCase() ;
if (node.exist(ch)){
node = node.get(ch) ;
arr.push(ch) ;
}
else {
return ans;
}
}
this.getWordsUtil(node,ans,arr) ;
return ans;
}
}
export default Trie;