File tree Expand file tree Collapse file tree 3 files changed +39
-33
lines changed
Expand file tree Collapse file tree 3 files changed +39
-33
lines changed Original file line number Diff line number Diff line change 11class Trie {
22 private map : Map < string , Trie > = new Map ( ) ;
3- constructor ( ) { }
43 insert ( word : string ) : void {
54 if ( word === "" ) {
65 this . map . set ( "#" , new Trie ( ) ) ;
Original file line number Diff line number Diff line change 1+ export default { } ;
2+
3+ function longestCommonPrefix ( strs : string [ ] ) : string {
4+ class TrieNode {
5+ isEnd = false ;
6+ mem : Map < string , TrieNode > = new Map ( ) ;
7+ }
8+
9+ class Trie {
10+ root : TrieNode = new TrieNode ( ) ;
11+ insert = ( str : string ) : void => {
12+ let ptr = this . root ;
13+ for ( const ch of str ) {
14+ if ( ! ptr . mem . has ( ch ) ) ptr . mem . set ( ch , new TrieNode ( ) ) ;
15+ ptr = ptr . mem . get ( ch ) ! ;
16+ }
17+ ptr . isEnd = true ;
18+ } ;
19+ searchPrefix = ( ) : string => {
20+ let ptr = this . root ;
21+ let ret = "" ;
22+ while (
23+ ptr &&
24+ ptr . mem . size === 1 /* multiple childs */ &&
25+ ptr . isEnd === false /* end condition*/
26+ ) {
27+ const key = ptr . mem . keys ( ) . next ( ) . value ;
28+ ret += key ;
29+ ptr = ptr . mem . get ( key ) ! ;
30+ }
31+ return ret ;
32+ } ;
33+ }
34+ const trie = new Trie ( ) ;
35+
36+ for ( const str of strs ) trie . insert ( str ) ;
37+
38+ return trie . searchPrefix ( ) ;
39+ }
Load Diff This file was deleted.
You can’t perform that action at this time.
0 commit comments