File tree Expand file tree Collapse file tree 1 file changed +70
-0
lines changed Expand file tree Collapse file tree 1 file changed +70
-0
lines changed Original file line number Diff line number Diff line change 1+ class TrieNode {
2+ constructor ( ) {
3+ this . children = { } ;
4+ this . isEnd = false ;
5+ }
6+ }
7+
8+ class MagicDictionary {
9+ constructor ( ) {
10+ this . root = new TrieNode ( ) ;
11+ }
12+
13+ /**
14+ * @param {string[] } dict
15+ * @return {void }
16+ */
17+ buildDict ( dict ) {
18+ dict . forEach ( word => {
19+ this . insert ( word ) ;
20+ } ) ;
21+ }
22+
23+ insert ( word ) {
24+ let current = this . root ;
25+ for ( let i = 0 ; i < word . length ; i ++ ) {
26+ const c = word [ i ] ;
27+ if ( ! current . children [ c ] ) {
28+ current . children [ c ] = new TrieNode ( ) ;
29+ }
30+ current = current . children [ c ] ;
31+ }
32+ current . isEnd = true ;
33+ }
34+
35+ /**
36+ * @param {string } word
37+ * @return {boolean }
38+ */
39+ search ( word ) {
40+ const letters = 'abcdefghijklmnopqrstuvwxyz' ;
41+
42+ for ( let i = 0 ; i < word . length ; i ++ ) {
43+ for ( let j = 0 ; j < letters . length ; j ++ ) {
44+ const letter = letters [ j ] ;
45+
46+ if ( word [ i ] !== letter ) {
47+ const modifiedWord = word . substr ( 0 , i ) + letter + word . substr ( i + 1 ) ;
48+
49+ if ( this . match ( modifiedWord ) ) {
50+ return true ;
51+ }
52+ }
53+ }
54+ }
55+
56+ return false ;
57+ }
58+
59+ match ( word ) {
60+ let current = this . root ;
61+ for ( let i = 0 ; i < word . length ; i ++ ) {
62+ const c = word [ i ] ;
63+ if ( ! current . children [ c ] ) {
64+ return false ;
65+ }
66+ current = current . children [ c ] ;
67+ }
68+ return current . isEnd ;
69+ }
70+ }
You can’t perform that action at this time.
0 commit comments