JavaScript版本压缩前缀树

压缩Trie的性质和优势:   

        与标准Trie比较,压缩Trie的结点数与串的个数成正比了,而不是与串的总长度成正比。

class TrieTree{
  constructor(str,tail) {
    this.val = str;
    this.tail = tail;
    this.child = new Array(26).fill(null);
  }
}
class CompreeTrieTree{
  constructor() {
    this.root=new TrieTree('')
  }
  insert=(str)=>{
    let root=this.root
    let _getcommonlen=(str1,str2)=>{
      let m=0;
      while (m<str1.length&&m<str2.length&&str1[m] == str2[m]) m++;
      return m;
    }
    let _insert=(str,node)=>{
        if(str=="") return node;
        let index=str[0].charCodeAt()-'a'.charCodeAt()
        let childnode=node.child[index]
        if(!childnode){
          node.child[index]=new TrieTree(str,true)
        }else{
          let nodeval=childnode.val
          let commonlen=_getcommonlen(nodeval,str)
          if(commonlen==str.length||commonlen==nodeval.length){
            node.child[index].tail=true;
          }else{
            node.child[index].tail=false;
          }
          node.child[index].val=str.substr(0,commonlen)
          node.child[index]=_insert(str.substr(commonlen),node.child[index])
          node.child[index]=_insert(nodeval.substr(commonlen),node.child[index])
        }
        return node
    }
    this.root=_insert(str,root,false)
  }
  find=(str)=>{
    /*
    * 查询
    * */
    let len=str.length
    let node=this.root
    for (let i = 0; i <len; i++) {
      let index=str[i].charCodeAt()-'a'.charCodeAt()
      let childnode=node.child[index]
      if(!childnode){
        return false
      }
      let nodeval=childnode.val
      if(str.substr(i).length<nodeval.val) return false
      if(str.substr(i,nodeval.length)!=nodeval){
        return false
      }
      if(nodeval==str.substr(i)&&childnode.tail){
        return true
      }
      i+=nodeval.length-1
      node=childnode
    }
    return false;
  }
}
const treetest=new CompreeTrieTree();
treetest.insert("abc")
treetest.insert("abcde")
treetest.insert("abcfe")
treetest.insert("bcaa")
treetest.insert("abcfed")
console.log(treetest.find("abcfedd"))
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值