|
| 1 | +/* |
| 2 | +words를 맵형태로 저장, 각 스펠링과 다음에 나오는 문자열을 key-value로 하는 맵으로 저장 |
| 3 | +.의 경우 모든 경우를 탐색한다 |
| 4 | +
|
| 5 | +시간복잡도 : |
| 6 | + addWord : O(L) (L은 words의 길이) |
| 7 | + search : 일반적으로 O(L), .이 많으면 O(26^k) (k는 .의 개수) |
| 8 | +
|
| 9 | +*/ |
| 10 | +class TrieNode { |
| 11 | + children: Map<string, TrieNode> |
| 12 | + isEnd: boolean |
| 13 | + |
| 14 | + constructor() { |
| 15 | + this.children = new Map() |
| 16 | + this.isEnd = false |
| 17 | + } |
| 18 | +} |
| 19 | + |
| 20 | +class WordDictionary { |
| 21 | + words = new TrieNode() |
| 22 | + constructor() {} |
| 23 | + |
| 24 | + addWord(word: string): void { |
| 25 | + let curWords = this.words |
| 26 | + |
| 27 | + for (let i = 0; i < word.length; i++) { |
| 28 | + const char = word[i] |
| 29 | + |
| 30 | + if (!curWords.children.has(char)) { |
| 31 | + curWords.children.set(char, new TrieNode()) |
| 32 | + } |
| 33 | + |
| 34 | + curWords = curWords.children.get(char) |
| 35 | + } |
| 36 | + curWords.isEnd = true |
| 37 | + } |
| 38 | + |
| 39 | + search(word: string): boolean { |
| 40 | + return this.searchRecursively(word, this.words) |
| 41 | + } |
| 42 | + |
| 43 | + searchRecursively(word: string, area: TrieNode) { |
| 44 | + for (let i = 0; i < word.length; i++) { |
| 45 | + if (!area) return false |
| 46 | + const char = word[i] |
| 47 | + |
| 48 | + if (char === '.') { |
| 49 | + const values = [...area.children.values()] |
| 50 | + |
| 51 | + for (let newArea of values) { |
| 52 | + const result = this.searchRecursively(word.slice(i + 1), newArea) |
| 53 | + if (result) return true |
| 54 | + } |
| 55 | + return false |
| 56 | + } else { |
| 57 | + if (!area.children.has(char)) return false |
| 58 | + area = area.children.get(char) |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + if (area.isEnd) return true |
| 63 | + return false |
| 64 | + } |
| 65 | +} |
| 66 | + |
| 67 | +/** |
| 68 | + * Your WordDictionary object will be instantiated and called as such: |
| 69 | + * var obj = new WordDictionary() |
| 70 | + * obj.addWord(word) |
| 71 | + * var param_2 = obj.search(word) |
| 72 | + */ |
0 commit comments