|
| 1 | +// 단순 구현 시 효율이 낮게 나옴 |
| 2 | +// class Trie { |
| 3 | +// private word: Set<string>; |
| 4 | +// constructor() { |
| 5 | +// this.word = new Set(); |
| 6 | +// } |
| 7 | + |
| 8 | +// insert(word: string): void { |
| 9 | +// this.word.add(word); |
| 10 | +// } |
| 11 | + |
| 12 | +// search(word: string): boolean { |
| 13 | +// return this.word.has(word); |
| 14 | +// } |
| 15 | + |
| 16 | +// startsWith(prefix: string): boolean { |
| 17 | +// for (const str of this.word) { |
| 18 | +// if (prefix.length > str.length) { |
| 19 | +// continue; |
| 20 | +// } |
| 21 | +// let check = true; |
| 22 | +// for (let i = 0; i < prefix.length; i++) { |
| 23 | +// if (str[i] !== prefix[i]) { |
| 24 | +// check = false; |
| 25 | +// break; |
| 26 | +// } |
| 27 | +// } |
| 28 | +// if (check) { |
| 29 | +// return true; |
| 30 | +// } |
| 31 | +// } |
| 32 | +// return false; |
| 33 | +// } |
| 34 | +// } |
| 35 | + |
| 36 | +// 노드 구조를 개선 |
| 37 | +class TrieNode { |
| 38 | + children: { [key: string]: TrieNode }; |
| 39 | + isEndOfWord: boolean; |
| 40 | + constructor() { |
| 41 | + this.children = {}; |
| 42 | + this.isEndOfWord = false; |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +class Trie { |
| 47 | + private root: TrieNode; |
| 48 | + constructor() { |
| 49 | + this.root = new TrieNode(); |
| 50 | + } |
| 51 | + |
| 52 | + insert(word: string): void { |
| 53 | + // 글자 하나씩 TrieNode 타입으로 저장 |
| 54 | + let currentNode = this.root; |
| 55 | + for (const char of word) { |
| 56 | + if (!currentNode.children[char]) { |
| 57 | + currentNode.children[char] = new TrieNode(); |
| 58 | + } |
| 59 | + |
| 60 | + currentNode = currentNode.children[char]; |
| 61 | + } |
| 62 | + currentNode.isEndOfWord = true; |
| 63 | + console.log(this.root); |
| 64 | + } |
| 65 | + |
| 66 | + // 각 글자를 TrieNode에서 서칭하며 판단 |
| 67 | + search(word: string): boolean { |
| 68 | + let currentNode = this.root; |
| 69 | + for (const char of word) { |
| 70 | + if (!currentNode.children[char]) { |
| 71 | + return false; |
| 72 | + } |
| 73 | + currentNode = currentNode.children[char]; |
| 74 | + } |
| 75 | + return currentNode.isEndOfWord; |
| 76 | + } |
| 77 | + |
| 78 | + // 동일 로직이지만 prefix 만큼만 존재하면 true |
| 79 | + startsWith(prefix: string): boolean { |
| 80 | + let currentNode = this.root; |
| 81 | + for (const char of prefix) { |
| 82 | + if (!currentNode.children[char]) { |
| 83 | + return false; |
| 84 | + } |
| 85 | + currentNode = currentNode.children[char]; |
| 86 | + } |
| 87 | + return true; |
| 88 | + } |
| 89 | +} |
| 90 | + |
| 91 | +const trie = new Trie(); |
| 92 | +trie.insert("apple"); |
| 93 | +trie.search("apple"); // true |
| 94 | +trie.search("app"); // false |
| 95 | +trie.startsWith("app"); // true |
| 96 | +trie.insert("app"); |
| 97 | +trie.search("app"); // true |
| 98 | + |
| 99 | + |
0 commit comments