Movatterモバイル変換


[0]ホーム

URL:


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

Commitcd99c8b

Browse files
authored
Improved task 208
1 parent8d2bdfd commitcd99c8b

File tree

1 file changed

+17
-21
lines changed
  • src/main/js/g0201_0300/s0208_implement_trie_prefix_tree

1 file changed

+17
-21
lines changed

‎src/main/js/g0201_0300/s0208_implement_trie_prefix_tree/solution.js‎

Lines changed: 17 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,59 +1,55 @@
1-
21
// #Medium #Top_100_Liked_Questions #Top_Interview_Questions #String #Hash_Table #Design #Trie
32
// #Level_2_Day_16_Design #Udemy_Trie_and_Heap
43
// #Big_O_Time_O(word.length())_or_O(prefix.length())_Space_O(N)
54
// #2024_12_17_Time_39_ms_(93.97%)_Space_66.4_MB_(88.79%)
65

76
varTrie=function(){
8-
this.root={}// Initialize root node as an empty object
9-
}
7+
this.root={};
8+
};
109

1110
/**
1211
*@param {string} word
1312
*@return {void}
1413
*/
1514
Trie.prototype.insert=function(word){
16-
letnode=this.root
17-
for(leti=0;i<word.length;i++){
18-
constchar=word[i]
15+
letnode=this.root;
16+
for(constcharofword){
1917
if(!node[char]){
20-
node[char]={}// Create a new node if it doesn't exist
18+
node[char]={};
2119
}
22-
node=node[char]// Move to the next node
20+
node=node[char];
2321
}
24-
node.isWord=true// Mark the node as a word endpoint
22+
node.isWord=true;
2523
};
2624

2725
/**
2826
*@param {string} word
2927
*@return {boolean}
3028
*/
3129
Trie.prototype.search=function(word){
32-
letnode=this.root
33-
for(leti=0;i<word.length;i++){
34-
constchar=word[i]
30+
letnode=this.root;
31+
for(constcharofword){
3532
if(!node[char]){
36-
returnfalse// Word doesn't exist
33+
returnfalse;
3734
}
38-
node=node[char]// Move to the next node
35+
node=node[char];
3936
}
40-
returnnode.isWord===true// Return true if it's a complete word
37+
returnnode.isWord===true;
4138
};
4239

4340
/**
4441
*@param {string} prefix
4542
*@return {boolean}
4643
*/
4744
Trie.prototype.startsWith=function(prefix){
48-
letnode=this.root
49-
for(leti=0;i<prefix.length;i++){
50-
constchar=prefix[i]
45+
letnode=this.root;
46+
for(constcharofprefix){
5147
if(!node[char]){
52-
returnfalse// Prefix doesn't exist
48+
returnfalse;
5349
}
54-
node=node[char]// Move to the next node
50+
node=node[char];
5551
}
56-
returntrue// Return true if prefix exists
52+
returntrue;
5753
};
5854

5955
/**

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp