|
| 1 | +/** |
| 2 | + * ๋ฌธ์ ์ ํ |
| 3 | + * - Trie ๊ตฌํ (๋ฌธ์์ด ๊ฒ์) |
| 4 | + * |
| 5 | + * ๋ฌธ์ ์ค๋ช
|
| 6 | + * - ๋ฌธ์์ด ๊ฒ์/์ถ์ฒ/์๋์์ฑ์์ ์์ฃผ ์ฌ์ฉํ๋ ์๋ฃ๊ตฌ์กฐ Trie ๊ตฌํ |
| 7 | + * |
| 8 | + * ์์ด๋์ด |
| 9 | + * 1) ๋ฌธ์์ด์ ๊ฐ ๋ฌธ์๋ฅผ TrieNode ํด๋์ค์ ์ธ์คํด์ค๋ก ํํs |
| 10 | + * |
| 11 | + */ |
| 12 | +class TrieNode { |
| 13 | + children: Map<string, TrieNode>; |
| 14 | + isEnd: boolean; |
| 15 | + |
| 16 | + constructor() { |
| 17 | + this.children = new Map(); |
| 18 | + this.isEnd = false; |
| 19 | + } |
| 20 | +} |
| 21 | + |
| 22 | +class Trie { |
| 23 | + root: TrieNode; |
| 24 | + constructor() { |
| 25 | + this.root = new TrieNode(); |
| 26 | + } |
| 27 | + |
| 28 | + insert(word: string): void { |
| 29 | + let node = this.root; |
| 30 | + for (const char of word) { |
| 31 | + if (!node.children.has(char)) { |
| 32 | + node.children.set(char, new TrieNode()); |
| 33 | + } |
| 34 | + node = node.children.get(char)!; |
| 35 | + } |
| 36 | + node.isEnd = true; |
| 37 | + } |
| 38 | + |
| 39 | + // isEnd ๊น์ง ํ์ธ์ด ํ์ |
| 40 | + search(word: string): boolean { |
| 41 | + const node = this._findNode(word); |
| 42 | + return node !== null && node.isEnd; |
| 43 | + } |
| 44 | + |
| 45 | + // isEnd๊น์ง ํ์ธ ํ์ ์๊ณ ์กด์ฌ ์ฌ๋ถ๋ง ํ์ธ ํ์ |
| 46 | + startsWith(prefix: string): boolean { |
| 47 | + return this._findNode(prefix) !== null; |
| 48 | + } |
| 49 | + |
| 50 | + private _findNode(word: string): TrieNode | null { |
| 51 | + let node = this.root; |
| 52 | + for (const char of word) { |
| 53 | + if (!node.children.get(char)) return null; |
| 54 | + node = node.children.get(char)!; |
| 55 | + } |
| 56 | + |
| 57 | + return node; |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +/** |
| 62 | + * Your Trie object will be instantiated and called as such: |
| 63 | + * var obj = new Trie() |
| 64 | + * obj.insert(word) |
| 65 | + * var param_2 = obj.search(word) |
| 66 | + * var param_3 = obj.startsWith(prefix) |
| 67 | + */ |
0 commit comments