|
| 1 | +/** |
| 2 | + * @class - Dictionary 구현 |
| 3 | + * @description |
| 4 | + * - .의 경우 모든 문자와 일치 |
| 5 | + * - .일 경우 결국 모든 children 조회필요 => dfs |
| 6 | + */ |
| 7 | + |
| 8 | +class WordNode { |
| 9 | + children: { [key: string]: WordNode }; |
| 10 | + endOfWord: boolean; |
| 11 | + constructor() { |
| 12 | + this.children = {}; |
| 13 | + this.endOfWord = false; |
| 14 | + } |
| 15 | +} |
| 16 | + |
| 17 | +class WordDictionary { |
| 18 | + private rootNode: WordNode; |
| 19 | + constructor() { |
| 20 | + this.rootNode = new WordNode(); |
| 21 | + } |
| 22 | + |
| 23 | + addWord(word: string): void { |
| 24 | + let nodeInstance = this.rootNode; |
| 25 | + |
| 26 | + for (const str of word) { |
| 27 | + if (!nodeInstance.children[str]) { |
| 28 | + nodeInstance.children[str] = new WordNode(); |
| 29 | + } |
| 30 | + nodeInstance = nodeInstance.children[str]; |
| 31 | + } |
| 32 | + |
| 33 | + nodeInstance.endOfWord = true; |
| 34 | + } |
| 35 | + |
| 36 | + search(word: string): boolean { |
| 37 | + return this.searchDfs(this.rootNode, word, 0); |
| 38 | + } |
| 39 | + |
| 40 | + private searchDfs(currentNode: WordNode, word: string, idx: number): boolean { |
| 41 | + if (idx === word.length) { |
| 42 | + return currentNode.endOfWord; |
| 43 | + } |
| 44 | + |
| 45 | + const char = word[idx]; |
| 46 | + if (char === ".") { |
| 47 | + for (const key in currentNode.children) { |
| 48 | + const childSearch = this.searchDfs( |
| 49 | + currentNode.children[key], |
| 50 | + word, |
| 51 | + idx + 1 |
| 52 | + ); |
| 53 | + if (childSearch) { |
| 54 | + return true; |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + return false; |
| 59 | + } else { |
| 60 | + if (!currentNode.children[char]) { |
| 61 | + return false; |
| 62 | + } |
| 63 | + |
| 64 | + return this.searchDfs(currentNode.children[char], word, idx + 1); |
| 65 | + } |
| 66 | + } |
| 67 | +} |
| 68 | + |
| 69 | +const wordDict = new WordDictionary(); |
| 70 | + |
| 71 | +wordDict.addWord("at"); |
| 72 | +wordDict.addWord("and"); |
| 73 | +wordDict.addWord("an"); |
| 74 | +wordDict.addWord("add"); |
| 75 | + |
| 76 | +wordDict.search("a"); // false |
| 77 | +wordDict.search(".at"); // false |
| 78 | + |
| 79 | +wordDict.addWord("bat"); |
| 80 | + |
| 81 | +wordDict.search(".at"); // true |
| 82 | +wordDict.search("an."); // true |
| 83 | +wordDict.search("a.d."); // false |
| 84 | +wordDict.search("b."); // false |
| 85 | +wordDict.search("a.d"); // true |
| 86 | +wordDict.search("."); // false |
| 87 | + |
| 88 | + |
| 89 | + |
0 commit comments