-
Notifications
You must be signed in to change notification settings - Fork 0
/
triePrefix.js
49 lines (42 loc) · 1.01 KB
/
triePrefix.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
class trieNode{
constructor(){
this.children={}
this.endOfWord=false
}
}
class trie{
constructor(){
this.root=new trieNode()
}
insert(word){
let node=this.root
for(let i=0;i<word.length;i++){
let char=word[i]
if(!node.children[char]){
node.children[char]=new trieNode
}node=node.children[char]
}node.endOfWord=true
}
search(word){
let node=this.root
for(let i=0;i<word.length;i++){
let char=word[i]
if(!node.children[char]){
return false
}node=node.children[char]
}return node.endOfWord
}
preffix(word){
let node=this.root
for(let i=0;i<word.length;i++){
let char=word[i]
if (!node.children[char]){
return false
}node=node.children[char]
}return true
}
}
let tr=new trie
tr.insert("azhar")
tr.insert("hello")
console.log(tr.preffix("har"))