-
-
Save evandocarmo/4331213a7d7e660dd2f112e9246adaf6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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