js实现字典树
//字典树和链表的区别,是node.next指向一个node 或 node[]的区别 function Node(){ this.next=[]; this.value= null; } function TrieST(){ this.root = new Node(); this.put = (key,value)=>{ _put(this.root, key ,value,0); } this.get = (key)=>{ let res = _get(this.root, key, 0); if(res === null || res === undefined){ return null;} return res.value; } this.contains = (key)=>{ let res = this.get(key); if(res !== null && res !== undefined ){ return true; } return false; } function _put (x,key,val,i) { //如果不存在,初始化 if(x === null || x === undefined){ x = new Node(); } //如果找到了,无论之前存在与否,更新它储存的值 if(i== key.length){ x.value = val;
return x; } //当前字符 let c = key.charAt(i); //下一个字符 //设定在X.next中,key[i]的值 x.next[c] =_put(x.next[c],key,val,i+1); //返回key[i]对应的Node到树中 return x; } function _get (x,key,i) { if(x=== null || x === undefined){ return null; } //如果当前值是要的值,返回 if(i == key.length){ return x; } let c = key.charAt(i); return _get(x.next[c],key,i+1); } }
let tries= new TrieST();
tries.put("heheh",10);
console.log(tries)
//...
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)