File tree Expand file tree Collapse file tree 1 file changed +55
-0
lines changed Expand file tree Collapse file tree 1 file changed +55
-0
lines changed Original file line number Diff line number Diff line change 1+ class TrieNode {
2+ constructor ( ) {
3+ this . children = { } ;
4+ this . endOfWord = false ;
5+ }
6+ }
7+
8+ class WordDictionary {
9+ constructor ( ) {
10+ this . root = new TrieNode ( ) ;
11+ }
12+
13+ addWord ( word ) {
14+ let cur = this . root ;
15+
16+ for ( const c of word ) {
17+ if ( ! ( c in cur . children ) ) {
18+ cur . children [ c ] = new TrieNode ( ) ;
19+ }
20+ cur = cur . children [ c ] ;
21+ }
22+ cur . endOfWord = true ;
23+ }
24+
25+ search ( word ) {
26+ function dfs ( j , root ) {
27+ let cur = root ;
28+
29+ for ( let i = j ; i < word . length ; i ++ ) {
30+ const c = word [ i ] ;
31+
32+ if ( c === "." ) {
33+ for ( const key in cur . children ) {
34+ if ( Object . prototype . hasOwnProperty . call ( cur . children , key ) ) {
35+ const child = cur . children [ key ] ;
36+
37+ if ( dfs ( i + 1 , child ) ) {
38+ return true ;
39+ }
40+ }
41+ }
42+ return false ;
43+ } else {
44+ if ( ! ( c in cur . children ) ) {
45+ return false ;
46+ }
47+ cur = cur . children [ c ] ;
48+ }
49+ }
50+
51+ return cur . endOfWord ;
52+ }
53+ return dfs ( 0 , this . root ) ;
54+ }
55+ }
You can’t perform that action at this time.
0 commit comments