|
| 1 | +class TrieNode: |
| 2 | + # 트라이 노드 |
| 3 | + def __init__(self): |
| 4 | + self.children = {} |
| 5 | + # 단어의 끝을 나타내기 위한 플래그 |
| 6 | + self.isEndOfWord = False |
| 7 | + |
| 8 | +class Trie: |
| 9 | + # 트라이 |
| 10 | + def __init__(self): |
| 11 | + self.root = TrieNode() |
| 12 | + |
| 13 | + def insert(self, word: str) -> None: |
| 14 | + # 삽입 연산 |
| 15 | + # Time Complexity: O(L) (L은 word의 길이) |
| 16 | + # Space Complexity: O(M) (M은 트라이에 삽입된 모든 단어들의 총 문자 개수 합) |
| 17 | + currentNode = self.root |
| 18 | + |
| 19 | + for char in word: |
| 20 | + if char not in currentNode.children: |
| 21 | + currentNode.children[char] = TrieNode() |
| 22 | + currentNode = currentNode.children[char] |
| 23 | + currentNode.isEndOfWord = True |
| 24 | + |
| 25 | + def search(self, word: str) -> bool: |
| 26 | + # 완전 검색 연산 |
| 27 | + # Time Complexity: O(L) (L은 word의 길이) |
| 28 | + # Space Complexity: O(M) |
| 29 | + currentNode = self.root |
| 30 | + for char in word: |
| 31 | + if char not in currentNode.children: |
| 32 | + return False |
| 33 | + currentNode = currentNode.children[char] |
| 34 | + return currentNode.isEndOfWord |
| 35 | + |
| 36 | + def startsWith(self, prefix: str) -> bool: |
| 37 | + # 접두사 일치 검사 연산 |
| 38 | + # Time Complexity: O(P) (P는 Prefix의 길이) |
| 39 | + # Space Complexity: O(M) |
| 40 | + currentNode = self.root |
| 41 | + for char in prefix: |
| 42 | + if char not in currentNode.children: |
| 43 | + return False |
| 44 | + currentNode = currentNode.children[char] |
| 45 | + return True |
| 46 | + |
| 47 | + |
| 48 | + |
| 49 | +# Your Trie object will be instantiated and called as such: |
| 50 | +# obj = Trie() |
| 51 | +# obj.insert(word) |
| 52 | +# param_2 = obj.search(word) |
| 53 | +# param_3 = obj.startsWith(prefix) |
0 commit comments