来看看Trie的JS实现
2020-09-10 本文已影响0人
ahalshai
class trieNode{
constructor(val = null){
this.sibling = [];
this.val = val
this.isEnd = false;
}
}
class Trie{
constructor:{
this.root = new trieNode()
}
add(word){
let cur = this.root
for (let i of word){
let tmp = cur.sibling[i] || new trieNode(i);
cur.sibling[i] = tmp;
cur = tmp;
}
cur.isEnd = True
}
search(word){
let cur = this.root
for(let i of word){
if(cur[i]) cur = cur.sibling[i];
else return false;
}
return cur.isEnd
}
prefix(word){
let cur = this.root
for(let i of word){
if(cur[i]) cur = cur.sibling[i];
else return false;
}
return true
}
}