Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit a3cafc8

Browse files
committed
update: trie search()
1 parent 5914947 commit a3cafc8

File tree

1 file changed

+38
-4
lines changed
  • src/_DataStructures_/Trees/Trie

1 file changed

+38
-4
lines changed

‎src/_DataStructures_/Trees/Trie/index.js‎

Lines changed: 38 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,12 @@ class Trie {
55
this.root = new Node('');
66
}
77

8+
// helper to get the index of a character
9+
// eslint-disable-next-line class-methods-use-this
10+
getIndexOfChar(char) {
11+
return char.charCodeAt(0) - 'a'.charCodeAt(0);
12+
}
13+
814
insert(key) {
915
if (!key) {
1016
return false;
@@ -29,11 +35,39 @@ class Trie {
2935
return true;
3036
}
3137

32-
// helper to get the index of a character
33-
// eslint-disable-next-line class-methods-use-this
34-
getIndexOfChar(char) {
35-
return char.charCodeAt(0) - 'a'.charCodeAt(0);
38+
search(key) {
39+
if (!key) {
40+
return false;
41+
}
42+
43+
// convert word to lower case
44+
const word = key.toLowerCase();
45+
let currentNode = this.root;
46+
47+
for (let level = 0; level < word.length; level += 1) {
48+
const index = this.getIndexOfChar(word[level]);
49+
if (!currentNode.children[index]) {
50+
return false;
51+
}
52+
currentNode = currentNode.children[index];
53+
}
54+
if (currentNode !== null && currentNode.isEndOfWord) {
55+
return true;
56+
}
57+
return false;
3658
}
3759
}
3860

61+
const words = ['bed', 'ball', 'apple', 'java', 'javascript'];
62+
const trie = new Trie();
63+
64+
words.forEach(word => trie.insert(word));
65+
66+
console.log(trie.root);
67+
68+
console.log(trie.search(words[3]));
69+
console.log(trie.search('word'));
70+
console.log(trie.search(words[4]));
71+
console.log(trie.search('random'));
72+
3973
module.exports = Trie;

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /