File tree Expand file tree Collapse file tree 1 file changed +54
-0
lines changed
implement-trie-prefix-tree Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * 트라이 알고리즘
3+ * 달레 해설을 보고 참고하여 TypeScript로 작성
4+ */
5+ class Node {
6+ children : { [ key : string ] : Node } ;
7+ ending : boolean ;
8+
9+ constructor ( ending : boolean = false ) {
10+ this . children = { } ;
11+ this . ending = ending ;
12+ }
13+ }
14+
15+ class Trie {
16+ private root : Node ;
17+
18+ constructor ( ) {
19+ this . root = new Node ( true ) ;
20+ }
21+
22+ insert ( word : string ) : void {
23+ let node = this . root ;
24+ for ( const ch of word ) {
25+ if ( ! ( ch in node . children ) ) {
26+ node . children [ ch ] = new Node ( ) ;
27+ }
28+ node = node . children [ ch ] ;
29+ }
30+ node . ending = true ;
31+ }
32+
33+ search ( word : string ) : boolean {
34+ let node = this . root ;
35+ for ( const ch of word ) {
36+ if ( ! ( ch in node . children ) ) {
37+ return false ;
38+ }
39+ node = node . children [ ch ] ;
40+ }
41+ return node . ending ;
42+ }
43+
44+ startsWith ( prefix : string ) : boolean {
45+ let node = this . root ;
46+ for ( const ch of prefix ) {
47+ if ( ! ( ch in node . children ) ) {
48+ return false ;
49+ }
50+ node = node . children [ ch ] ;
51+ }
52+ return true ;
53+ }
54+ }
You can’t perform that action at this time.
0 commit comments