File tree Expand file tree Collapse file tree 1 file changed +54
-0
lines changed
design-add-and-search-words-data-structure Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Original file line number Diff line number Diff line change
1
+ var WordDictionary = function ( ) {
2
+ this . root = { } ;
3
+ } ;
4
+
5
+ /**
6
+ * @param {string } word
7
+ * @return {void }
8
+ */
9
+ WordDictionary . prototype . addWord = function ( word ) {
10
+ let node = this . root ;
11
+ for ( const char of word ) {
12
+ if ( ! node [ char ] ) {
13
+ // ํ์ฌ ๋ฌธ์์ ํด๋นํ๋ ๋
ธ๋๊ฐ ์์ผ๋ฉด ์๋ก ์์ฑ
14
+ node [ char ] = { isEnd : false } ;
15
+ }
16
+ node = node [ char ] ; // ๋ค์ ๋
ธ๋๋ก ์ด๋
17
+ }
18
+ node . isEnd = true ; // ๋จ์ด ๋ ํ์
19
+ } ;
20
+
21
+ /**
22
+ * @param {string } word
23
+ * @return {boolean }
24
+ */
25
+ WordDictionary . prototype . search = function ( word ) {
26
+ function dfs ( node , index ) {
27
+ // ๋จ์ด์ ๋์ ๋๋ฌํ์ผ๋ฉด isEnd ๊ฐ ๋ฐํ
28
+ if ( index === word . length ) return node . isEnd ;
29
+
30
+ const char = word [ index ] ;
31
+
32
+ if ( node [ char ] ) {
33
+ // ํ์ฌ ๋ฌธ์๊ฐ ๋
ธ๋์ ์กด์ฌํ๋ฉด ํด๋น ๋
ธ๋๋ก ์ด๋ํ์ฌ ๊ณ์ ๊ฒ์
34
+ return dfs ( node [ char ] , index + 1 ) ;
35
+ }
36
+
37
+ if ( char === "." ) {
38
+ // "."์ธ ๊ฒฝ์ฐ: ๋ชจ๋ ๊ฐ๋ฅํ ๋ฌธ์์ ๋ํด ๊ฒ์ ์๋
39
+ return Object . keys ( node )
40
+ . filter ( ( key ) => key !== "isEnd" )
41
+ . some ( ( key ) => dfs ( node [ key ] , index + 1 ) ) ; // ํ๋๋ผ๋ true๋ฅผ ๋ฐํํ๋ฉด true
42
+ }
43
+
44
+ return false ;
45
+ }
46
+ return dfs ( this . root , 0 ) ;
47
+ } ;
48
+
49
+ /**
50
+ * Your WordDictionary object will be instantiated and called as such:
51
+ * var obj = new WordDictionary()
52
+ * obj.addWord(word)
53
+ * var param_2 = obj.search(word)
54
+ */
You canโt perform that action at this time.
0 commit comments