Skip to content

Instantly share code, notes, and snippets.

@evandocarmo
Last active August 20, 2017 21:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save evandocarmo/4331213a7d7e660dd2f112e9246adaf6 to your computer and use it in GitHub Desktop.
Save evandocarmo/4331213a7d7e660dd2f112e9246adaf6 to your computer and use it in GitHub Desktop.
class Node {
constructor(char = null) {
this.children = {};
this.wordsInChildren = 0;
this.isCompleteWord = false;
this.value = char;
}
}
class Try {
constructor() {
this.root = new Node();
}
insert(word) {
let node = this.root;
for (let i = 0; i < word.length; i++) {
let char = word[i];
if (!node.children[char])
node.children[char] = new Node(char);
if (i === (word.length - 1))
node.children[char].isCompleteWord = true;
node.wordsInChildren += 1;
node = node.children[char];
}
}
find(word) {
let node = this.root;
let count = 0;
for (let char of word) {
if (node.children[char]) {
node = node.children[char];
} else
return 0;
}
count += node.isCompleteWord ? 1 : 0;
return count + node.wordsInChildren;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment