1
+ class Node {
2
+ constructor ( key = "" , value = null ) {
3
+ this . key = key ;
4
+ this . value = value ;
5
+ this . children = new Map ( ) ;
6
+ }
7
+ }
8
+ class Trie {
9
+ constructor ( ) {
10
+ this . root = new Node ( ) ;
11
+ }
12
+ insert ( text ) {
13
+ let currentNode = this . root ;
14
+ for ( let i = 0 ; i < text . length ; i ++ ) {
15
+ const char = text [ i ] ;
16
+ if ( ! currentNode . children . has ( char ) ) {
17
+ const key = currentNode . key + char ;
18
+ const isLastWordIndex = i === text . length - 1 ;
19
+ const value = isLastWordIndex ? currentNode . key + char : null ;
20
+ currentNode . children . set ( char , new Node ( key , value ) ) ;
21
+ }
22
+ currentNode = currentNode . children . get ( char ) ;
23
+ }
24
+ }
25
+ has ( text ) {
26
+ let currentNode = this . root ;
27
+ for ( const char of text ) {
28
+ currentNode = currentNode . children . get ( char ) ;
29
+ if ( currentNode === false ) {
30
+ return false ;
31
+ }
32
+ }
33
+ return currentNode . value === text ;
34
+ }
35
+ autoComplete ( text ) {
36
+ let currentNode = this . root ;
37
+ const children = [ ] ;
38
+
39
+ for ( const char of text ) {
40
+ currentNode = currentNode . children . get ( char ) ;
41
+ if ( currentNode === false ) {
42
+ console . log ( "not found node!" ) ;
43
+ return [ ] ;
44
+ }
45
+ }
46
+
47
+ function recursion ( node ) {
48
+ if ( node . value ) {
49
+ children . push ( node . value ) ;
50
+ }
51
+ if ( node . children . size ) {
52
+ node . children . forEach ( ( el ) => {
53
+ recursion ( el ) ;
54
+ } ) ;
55
+ }
56
+ }
57
+ recursion ( currentNode ) ;
58
+ return children ;
59
+ }
60
+ }
61
+
62
+ function solution ( phone_book ) {
63
+ var answer = true ;
64
+
65
+ const trie = new Trie ( ) ;
66
+
67
+ phone_book . sort ( ( a , b ) => b . length - a . length ) ;
68
+
69
+ for ( i = 0 ; i < phone_book . length ; i ++ ) {
70
+ const num = phone_book [ i ]
71
+
72
+ trie . insert ( num ) ;
73
+
74
+ const temp = trie . autoComplete ( num ) ;
75
+
76
+ if ( temp . length && temp [ 0 ] !== num ) {
77
+ answer = false ;
78
+ break ;
79
+ }
80
+ }
81
+
82
+ return answer
83
+ }
0 commit comments