-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrie.js
More file actions
72 lines (65 loc) · 1.45 KB
/
trie.js
File metadata and controls
72 lines (65 loc) · 1.45 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
class Trie{
constructor(){
this.root = new TrieNode('');
}
}
class TrieNode{
constructor(val){
this.val = val;
this.isWord = false;
this.children = {};
}
}
Trie.prototype.insert = function(word){
if(!word){
return false;
}
this.root.insert(word);
return this;
}
Trie.prototype.contains = function(word){
if(!word){
return false;
}
return this.root.contains(word);
}
TrieNode.prototype.insert = function(word, upto){
var at_end = false;
if(!upto){
var upto = word[0];
}
if(word.length == upto.length){
at_end = true;
}
var checkChar = word[upto.length-1];
if(!this.children[checkChar]){
this.children[checkChar] = new TrieNode(checkChar);
}
if(at_end){
this.children[checkChar].isWord = true;
return this;
}
else{
this.children[checkChar].insert(word, upto + word[upto.length])
}
}
TrieNode.prototype.contains = function(word, upto){
if(!upto){
var upto = word[0];
}
var node = this.children[word[upto.length-1]];
if(node){
if(word.length == upto.length && node.isWord){
return true;
}
upto += word[upto.length];
return node.contains(word, upto);
}
else{
return false;
}
}
var trie = new Trie();
console.log(trie.insert("cat"));
console.log(trie.insert("cane"));
console.log(trie.contains("cane"));