Trie树
程序员文章站
2022-06-27 21:59:08
```js
class TrieNode { constructor(data){ this.data = data this.children = new Array(26) this.isEndingChar = false this.text = '' }
} class TrieTree {... ......
class trienode { constructor(data){ this.data = data this.children = new array(26) this.isendingchar = false this.text = '' } } class trietree { constructor(){ this.root = new trienode('/') } insert(text){ let currentnode = this.root for(let char of text){ let index = char.charcodeat() - 'a'.charcodeat() if(!currentnode.children[index]){ currentnode.children[index] = new trienode(char) } currentnode = currentnode.children[index] } currentnode.isendingchar = true currentnode.text = text } find(text){ let currentnode = this.root for(let char of text){ let index = char.charcodeat() - 'a'.charcodeat() if(currentnode.children[index]){ currentnode = currentnode.children[index] } else { return { input:text, result: false } } } return { input:currentnode.text, result:currentnode.isendingchar } } } let tree = new trietree() let strs = ["how", "hi", "her", "hello", "so", "see"]; for(let str of strs) { tree.insert(str); } for(let str of strs) { console.log(tree.find(str)); } console.log(tree.find('world'));