Skip to content

Commit

Permalink
Merge pull request wangzheng0822#247 from WayneCui/master
Browse files Browse the repository at this point in the history
add simple trie of JS version
  • Loading branch information
wangzheng0822 authored Feb 22, 2019
2 parents 7a1b4d8 + 7babaf7 commit 88a2836
Showing 1 changed file with 56 additions and 0 deletions.
56 changes: 56 additions & 0 deletions javascript/35_trie/trie.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@


class TrieNode {
constructor(data){
this.data = data;
this.children = new Array(26);
this.isEndingChar = false
}
}

class TrieTree {

constructor(data){
this.root = new TrieNode('/')
}

insert (text) {
let node = this.root;
for (let char of text) {
let index = char.charCodeAt() - 'a'.charCodeAt();
if(!node.children[index]) {
node.children[index] = new TrieNode(char);
}
node = node.children[index];
}

node.isEndingChar = true;
}

find (text) {
let node = this.root;

for(let char of text) {
let index = char.charCodeAt() - 'a'.charCodeAt();
if(node.children[index]) {
node = node.children[index];
} else {
return false;
}
}

return node.isEndingChar;
}
}

var tree = new TrieTree();
var 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'));

0 comments on commit 88a2836

Please sign in to comment.