File tree Expand file tree Collapse file tree 1 file changed +17
-21
lines changed
src/main/js/g0201_0300/s0208_implement_trie_prefix_tree Expand file tree Collapse file tree 1 file changed +17
-21
lines changed Original file line number Diff line number Diff line change 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
76var Trie = 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 */
1514Trie . prototype . insert = function ( word ) {
16- let node = this . root
17- for ( let i = 0 ; i < word . length ; i ++ ) {
18- const char = word [ i ]
15+ let node = this . root ;
16+ for ( const char of word ) {
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 */
3129Trie . prototype . search = function ( word ) {
32- let node = this . root
33- for ( let i = 0 ; i < word . length ; i ++ ) {
34- const char = word [ i ]
30+ let node = this . root ;
31+ for ( const char of word ) {
3532 if ( ! node [ char ] ) {
36- return false // Word doesn't exist
33+ return false ;
3734 }
38- node = node [ char ] // Move to the next node
35+ node = node [ char ] ;
3936 }
40- return node . isWord === true // Return true if it's a complete word
37+ return node . isWord === true ;
4138} ;
4239
4340/**
4441 * @param {string } prefix
4542 * @return {boolean }
4643 */
4744Trie . prototype . startsWith = function ( prefix ) {
48- let node = this . root
49- for ( let i = 0 ; i < prefix . length ; i ++ ) {
50- const char = prefix [ i ]
45+ let node = this . root ;
46+ for ( const char of prefix ) {
5147 if ( ! node [ char ] ) {
52- return false // Prefix doesn't exist
48+ return false ;
5349 }
54- node = node [ char ] // Move to the next node
50+ node = node [ char ] ;
5551 }
56- return true // Return true if prefix exists
52+ return true ;
5753} ;
5854
5955/**
You can’t perform that action at this time.
0 commit comments