Trie字典树(js)
作者:
五十四十三十
,
2024-01-07 13:08:37
,
所有人可见
,
阅读 59
class TrieNode {
constructor(){
this.children = new Array(26).fill(null)
this.isEnd = false
}
}
class Trie {
constructor(){
root = new TrieNode()
}
insert (word) {
let p = this.root
for(let i = 0; i < word.length; i++){
const cur = word[i].charCodeAt() - 'a'.charCodeAt()
if(!p.children[cur]){
p.children[cur] = new TrieNode()
}
p = p.children[cur]
}
p.isEnd = true
};
search (word) {
let p = this.root
for(let i = 0; i < word.length; i++){
const cur = word[i].charCodeAt() - 'a'.charCodeAt()
if(!p.children[cur]) return false
p = p.children[cur]
}
return p.isEnd
};
startsWith (prefix) {
let p = this.root
for(let i = 0; i < prefix.length; i++){
const cur = prefix[i].charCodeAt() - 'a'.charCodeAt()
if(!p.children[cur]) return false
p = p.children[cur]
}
return true
};
}