|
| 1 | +from unittest import TestCase, main |
| 2 | + |
| 3 | + |
| 4 | +class Node: |
| 5 | + |
| 6 | + def __init__(self, key): |
| 7 | + self.key = key |
| 8 | + self.isWordEnd = False |
| 9 | + self.children = {} |
| 10 | + |
| 11 | + |
| 12 | +class Trie: |
| 13 | + WILD_CARD = '.' |
| 14 | + |
| 15 | + def __init__(self): |
| 16 | + self.root = Node(None) |
| 17 | + |
| 18 | + def insert(self, word: str) -> None: |
| 19 | + curr_node = self.root |
| 20 | + for char in word: |
| 21 | + if char not in curr_node.children: |
| 22 | + curr_node.children[char] = Node(char) |
| 23 | + |
| 24 | + curr_node = curr_node.children[char] |
| 25 | + curr_node.isWordEnd = True |
| 26 | + |
| 27 | + def search(self, node: Node, word: str, idx: int) -> bool: |
| 28 | + if idx == len(word): |
| 29 | + return node.isWordEnd |
| 30 | + |
| 31 | + for idx in range(idx, len(word)): |
| 32 | + if word[idx] == self.WILD_CARD: |
| 33 | + for child in node.children.values(): |
| 34 | + if self.search(child, word, idx + 1) is True: |
| 35 | + return True |
| 36 | + else: |
| 37 | + return False |
| 38 | + |
| 39 | + if word[idx] in node.children: |
| 40 | + return self.search(node.children[word[idx]], word, idx + 1) |
| 41 | + else: |
| 42 | + return False |
| 43 | + |
| 44 | + |
| 45 | +""" |
| 46 | +Runtime: 1810 ms (Beats 22.46%) |
| 47 | +Time Complexity: |
| 48 | + > addWord: word의 길이만큼 순회하므로 O(L) |
| 49 | + > search: |
| 50 | + - word의 평균 길이를 W이라하면, |
| 51 | + - '.'가 포함되어 있지 않는 경우 O(W), early return 가능하므로 upper bound |
| 52 | + - '.'가 포함되어 있는 경우, 해당 노드의 child만큼 재귀, trie의 평균 자식 수를 C라 하면 O(W) * O(C), early return 가능하므로 upper bound |
| 53 | + - trie의 평균 자식 수는 addWord의 실행횟수 C'에 선형적으로 비레(겹치는 char가 없는 경우 upper bound) |
| 54 | + > O(W) * O(C) ~= O(W) * O(C') ~= O(W * C'), upper bound |
| 55 | +
|
| 56 | +Memory: 66.78 MB (Beats 12.26%) |
| 57 | +Space Complexity: O(1) |
| 58 | + > addWord: |
| 59 | + - 삽입한 word의 평균 길이 L만큼 Node가 생성 및 Trie에 추가, O(L) |
| 60 | + - addWord의 실행횟수 C'에 비례, O(C') |
| 61 | + > O(L) * O(C') ~= O(L * C') |
| 62 | + > search: |
| 63 | + > 만들어진 Trie와 패러미터 word, 정수 변수 idx를 사용하므로 O(1) |
| 64 | + |
| 65 | +""" |
| 66 | +class WordDictionary: |
| 67 | + |
| 68 | + def __init__(self): |
| 69 | + self.trie = Trie() |
| 70 | + |
| 71 | + def addWord(self, word: str) -> None: |
| 72 | + self.trie.insert(word) |
| 73 | + |
| 74 | + def search(self, word: str) -> bool: |
| 75 | + return self.trie.search(self.trie.root, word, 0) |
| 76 | + |
| 77 | + |
| 78 | +class _LeetCodeTestCases(TestCase): |
| 79 | + def test_1(self): |
| 80 | + wordDictionary = WordDictionary() |
| 81 | + wordDictionary.addWord("at") |
| 82 | + self.assertEqual(wordDictionary.search(".at"), False) |
| 83 | + |
| 84 | + |
| 85 | +if __name__ == '__main__': |
| 86 | + main() |
0 commit comments