1
+ //https://github.com/codeisneverodd/programmers-coding-test
2
+ //더 좋은 풀이가 존재할 수 있습니다.
3
+ //정답 1 - ryong9rrr
4
+ class Node {
5
+ constructor ( value = '' ) {
6
+ this . value = value
7
+ this . children = new Map ( )
8
+ this . count = 0
9
+ }
10
+ }
11
+
12
+ class Trie {
13
+ constructor ( ) {
14
+ this . root = new Node ( )
15
+ }
16
+
17
+ insert ( string ) {
18
+ let currentNode = this . root
19
+ for ( const char of string ) {
20
+ if ( ! currentNode . children . has ( char ) ) {
21
+ currentNode . children . set ( char , new Node ( currentNode . value + char ) )
22
+ }
23
+ currentNode = currentNode . children . get ( char )
24
+ currentNode . count ++
25
+ }
26
+ }
27
+
28
+ startsWithCount ( prefix ) {
29
+ let currentNode = this . root
30
+ for ( const char of prefix ) {
31
+ if ( ! currentNode . children . has ( char ) ) {
32
+ return 0
33
+ }
34
+ currentNode = currentNode . children . get ( char )
35
+ }
36
+ return currentNode . count
37
+ }
38
+ }
39
+
40
+ function reverseString ( string ) {
41
+ return [ ...string ] . reverse ( ) . join ( '' )
42
+ }
43
+
44
+ function solution ( words , queries ) {
45
+ const table = { }
46
+ const reverseTable = { }
47
+ const counter = { }
48
+
49
+ words . forEach ( ( word ) => {
50
+ const key = word . length
51
+ if ( ! table [ key ] ) table [ key ] = new Trie ( )
52
+ if ( ! reverseTable [ key ] ) reverseTable [ key ] = new Trie ( )
53
+ table [ key ] . insert ( word )
54
+ reverseTable [ key ] . insert ( reverseString ( word ) )
55
+ if ( counter [ key ] === undefined ) counter [ key ] = 0
56
+ counter [ key ] ++
57
+ } )
58
+
59
+ return queries . map ( ( query ) => {
60
+ const key = query . length
61
+ if ( ! table [ key ] ) {
62
+ return 0
63
+ }
64
+ const tQuery = query . replace ( / \? / g, '' )
65
+ if ( ! tQuery ) {
66
+ return counter [ key ]
67
+ }
68
+ if ( query [ query . length - 1 ] === '?' ) {
69
+ return table [ key ] . startsWithCount ( tQuery )
70
+ }
71
+ return reverseTable [ key ] . startsWithCount ( reverseString ( tQuery ) )
72
+ } )
73
+ }
0 commit comments