美文网首页
来看看Trie的JS实现

来看看Trie的JS实现

作者: ahalshai | 来源:发表于2020-09-10 22:30 被阅读0次
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
  }
}

相关文章

网友评论

      本文标题:来看看Trie的JS实现

      本文链接:https://www.haomeiwen.com/subject/rrvlektx.html