字典树-javascrpit实现
来源:互联网 发布:名录搜索软件 编辑:程序博客网 时间:2024/04/28 08:33
var log = console.log;var Node = function(data) {this.data = data;// 存储单个字符this.childList = [];// 子节点列表this.wordFlag = false;// 表示从根到当前节点可以表示一个串};// 根据字符索引到对应的子节点,如果没找到返回-1Node.prototype.indexOf = function(data) {for(var i = 0; i < this.childList.length; i++) {if(this.childList[i].data == data) {return i;}}return -1;};// 字典树var TrieTree = function() {this.root = new Node(); // 树根};// 添加单词TrieTree.prototype.addWord = function(word) {var pNode = this.root;for(var i = 0; i < word.length; i++) {var char = word[i];var index = pNode.indexOf(char);if(index >= 0) {// 找到子节点pNode = pNode.childList[index];} else { // 没有这个字符,插入节点var node = new Node(char);pNode.childList.push(node);pNode = node;}}if(pNode != this.root) {pNode.wordFlag = true;}};// 查找TrieTree.prototype.searchWord = function(word) {var pNode = this.root;for(var i = 0; i < word.length; i++) {var char = word[i];var index = pNode.indexOf(char);if(index >= 0) {pNode = pNode.childList[index];} else {return [];}}var prefix = word.substring(0, word.length - 1);var wordList = this.deepSearch(pNode);for(var i = 0; i < wordList.length; i++) {wordList[i] = prefix + wordList[i];}return wordList;};// 深度优先查找TrieTree.prototype.deepSearch = function(node) {var wordList = [];if(node.childList.length > 0) {for(var i = 0; i < node.childList.length; i++) {var childDataList = this.deepSearch(node.childList[i]);for(var j = 0; j < childDataList.length; j++) {wordList.push(node.data + childDataList[j]);}}}if(node.wordFlag) {wordList.push(node.data);}return wordList;};var strList = ["a","abandon","abbreviation","ability","abide","above","adult","ab"];var trieTree = new TrieTree();for(var i = 0; i < strList.length; i++) {trieTree.addWord(strList[i]);}log(trieTree.searchWord("ab"))
0 0
- 字典树-javascrpit实现
- Java实现字典树
- 字典树实现
- 字典树数组实现
- 字典树的实现
- 字典树简单实现
- 字典树 python实现
- 字典树 c++ 实现
- 字典树的实现
- trie字典树实现
- python实现字典树
- 字典树的实现
- JavaScrpit Chart
- javaScrpit基本功能
- 字典树实现map容器
- 字典树的动态实现
- 字典树 Trie 的实现
- java字典树 实现统计
- python—pandas中DataFrame类型数据操作函数
- 登录页面样板
- 认识 UART 接口
- 触摸屏校正原理
- winXP/win7/win10系统关闭445端口方法全攻略
- 字典树-javascrpit实现
- heap和stack的区别
- ehcache的使用
- RxJava2 / RxAndroid2的merge操作合并多个Observable
- js兼容IE下载图片在本地
- Java连接Mysql数据库警告:Establishing SSL connection without server's identity verification is not recommend
- mingw64+msys编译64位ffmpeg
- 使用jrtplib(RTP)传输H.264视频文件(2)
- tensorflow46 《面向机器智能的TensorFlow实战》笔记-03-01 TensorBoard基本操作