File tree Expand file tree Collapse file tree 1 file changed +55
-0
lines changed
implement-trie-prefix-tree Expand file tree Collapse file tree 1 file changed +55
-0
lines changed Original file line number Diff line number Diff line change 1+ type ChildTrie = {
2+ value ?: string ;
3+ isEnd ?: boolean ;
4+ childrens : ChildrenMap ;
5+ } ;
6+ type ChildrenMap = {
7+ [ key : string ] : ChildTrie ;
8+ } ;
9+
10+ class Trie {
11+ childrens : ChildrenMap = { } ;
12+ constructor ( ) { }
13+
14+ insert ( word : string ) : void {
15+ if ( word . length === 0 ) {
16+ return ;
17+ }
18+ let current : ChildTrie = {
19+ childrens : this . childrens ,
20+ } ;
21+ for ( let i = 0 ; i < word . length ; i ++ ) {
22+ if ( current . childrens [ word [ i ] ] === undefined ) {
23+ current . childrens [ word [ i ] ] = { value : word [ i ] , isEnd : false , childrens : { } } ;
24+ }
25+
26+ current = current . childrens [ word [ i ] ] ;
27+ }
28+ current . isEnd = true ;
29+ }
30+
31+ search ( word : string ) : boolean {
32+ let current : ChildTrie = {
33+ childrens : this . childrens ,
34+ } ;
35+ for ( let i = 0 ; i < word . length ; i ++ ) {
36+ if ( current . childrens [ word [ i ] ] === undefined ) {
37+ return false ;
38+ }
39+
40+ current = current . childrens [ word [ i ] ] ;
41+ }
42+ return current . isEnd ?? false ;
43+ }
44+
45+ startsWith ( prefix : string ) : boolean {
46+ let current = this . childrens ;
47+ for ( let i = 0 ; i < prefix . length ; i ++ ) {
48+ if ( current [ prefix [ i ] ] === undefined ) {
49+ return false ;
50+ }
51+ current = current [ prefix [ i ] ] . childrens ;
52+ }
53+ return true ;
54+ }
55+ }
You can’t perform that action at this time.
0 commit comments