File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed
design-add-and-search-words-data-structure Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change 1+ class TrieNode {
2+ constructor ( ) {
3+ this . children = { } ;
4+ this . word = 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+ for ( let c of word ) {
16+ if ( ! cur . children [ c ] ) {
17+ cur . children [ c ] = new TrieNode ( ) ;
18+ }
19+ cur = cur . children [ c ] ;
20+ }
21+ cur . word = true ;
22+ }
23+
24+ search ( word ) {
25+ const dfs = ( j , root ) => {
26+ let cur = root ;
27+ for ( let i = j ; i < word . length ; i ++ ) {
28+ const c = word [ i ] ;
29+ if ( c === '.' ) {
30+ for ( let child of Object . values ( cur . children ) ) {
31+ if ( dfs ( i + 1 , child ) ) {
32+ return true ;
33+ }
34+ }
35+ return false ;
36+ } else {
37+ if ( ! cur . children [ c ] ) {
38+ return false ;
39+ }
40+ cur = cur . children [ c ] ;
41+ }
42+ }
43+ return cur . word ;
44+ } ;
45+ return dfs ( 0 , this . root ) ;
46+ }
47+ }
You can’t perform that action at this time.
0 commit comments