|
| 1 | +/** |
| 2 | + * |
| 3 | + * 문제 설명 |
| 4 | + * - 문자열 추가/검색에 효율적인 데이터 구조 설계 |
| 5 | + * |
| 6 | + * 아이디어 |
| 7 | + * 1) 배열에 추가, 순차적으로 검색(.의 경우 정규식 사용) |
| 8 | + * - Time Limit Exceeded (TLE) 발생 |
| 9 | + * |
| 10 | + * 2) Trie 구조로 저장, 검색은 dfs |
| 11 | + * - 문자열 검색어 최적화 = Trie |
| 12 | + * |
| 13 | + */ |
| 14 | + |
| 15 | +class TrieNode { |
| 16 | + children: Map<string, TrieNode> = new Map(); |
| 17 | + isEnd: boolean = false; |
| 18 | +} |
| 19 | + |
| 20 | +class WordDictionary { |
| 21 | + root: TrieNode; |
| 22 | + |
| 23 | + constructor() { |
| 24 | + this.root = new TrieNode(); |
| 25 | + } |
| 26 | + |
| 27 | + addWord(word: string): void { |
| 28 | + let node = this.root; |
| 29 | + for (let char of word) { |
| 30 | + if (!node.children.has(char)) { |
| 31 | + node.children.set(char, new TrieNode()); |
| 32 | + } |
| 33 | + node = node.children.get(char)!; |
| 34 | + } |
| 35 | + node.isEnd = true; |
| 36 | + } |
| 37 | + |
| 38 | + search(word: string): boolean { |
| 39 | + const dfs = (node: TrieNode, i: number) => { |
| 40 | + if (i === word.length) return node.isEnd; |
| 41 | + |
| 42 | + const char = word[i]; |
| 43 | + |
| 44 | + if (char === ".") { |
| 45 | + for (let child of node.children.values()) { |
| 46 | + if (dfs(child, i + 1)) return true; |
| 47 | + } |
| 48 | + return false; |
| 49 | + } else { |
| 50 | + const next = node.children.get(char); |
| 51 | + return next ? dfs(next, i + 1) : false; |
| 52 | + } |
| 53 | + }; |
| 54 | + |
| 55 | + return dfs(this.root, 0); |
| 56 | + } |
| 57 | +} |
| 58 | + |
| 59 | +/** |
| 60 | + * Your WordDictionary object will be instantiated and called as such: |
| 61 | + * var obj = new WordDictionary() |
| 62 | + * obj.addWord(word) |
| 63 | + * var param_2 = obj.search(word) |
| 64 | + */ |
0 commit comments