File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed
implement-trie-prefix-tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change 1+ class TrieNode {
2+ children : Map < string , TrieNode > ;
3+ isEnd : boolean ;
4+
5+ constructor ( ) {
6+ this . children = new Map ( ) ;
7+ this . isEnd = false ;
8+ }
9+ }
10+
11+ class Trie {
12+ root : TrieNode ;
13+
14+ constructor ( ) {
15+ this . root = new TrieNode ( ) ;
16+ }
17+
18+ insert ( word : string ) : void {
19+ let node = this . root ;
20+ for ( const char of word ) {
21+ if ( ! node . children . has ( char ) ) {
22+ node . children . set ( char , new TrieNode ( ) ) ;
23+ }
24+ node = node . children . get ( char ) ! ;
25+ }
26+ node . isEnd = true ;
27+ }
28+
29+ search ( word : string ) : boolean {
30+ const node = this . _findNode ( word ) ;
31+ return node !== null && node . isEnd ;
32+ }
33+
34+ startsWith ( prefix : string ) : boolean {
35+ return this . _findNode ( prefix ) !== null ;
36+ }
37+
38+ private _findNode ( word : string ) : TrieNode | null {
39+ let node = this . root ;
40+ for ( const char of word ) {
41+ if ( ! node . children . has ( char ) ) return null ;
42+ node = node . children . get ( char ) ! ;
43+ }
44+ return node ;
45+ }
46+ }
You can’t perform that action at this time.
0 commit comments