https://leetcode.com/problems/implement-trie-prefix-tree/
Implement Trie (Prefix Tree) - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
그냥 트라이를 알고있냐 모르고있냐를 보는거같다.
그렇게 어렵지 않다. 트라이가 뭔지 알고 구현을 한번이라도 해봤으면 금방 푸는 문제.
class Node:
def __init__(self):
self.next = {}
self.isWord = False
class Trie:
def __init__(self):
self.root = Node()
def insert(self, word: str) -> None:
node = self.root
for ch in word:
if ch not in node.next:
node.next[ch] = Node()
node = node.next[ch]
node.isWord = True
def search(self, word: str) -> bool:
node = self.root
for ch in word:
if ch not in node.next:
return False
node = node.next[ch]
return node.isWord
def startsWith(self, prefix: str) -> bool:
node = self.root
for ch in prefix:
if ch not in node.next:
return False
node = node.next[ch]
return True
# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix)
'코딩 테스트 및 알고리즘 > leetcode for google' 카테고리의 다른 글
leetcode medium : Minimum Number of Operations to Sort a Binary Tree by Level (0) | 2022.11.18 |
---|---|
leetcode medium : Number of Subarrays With LCM Equal to K (0) | 2022.11.17 |
leetcode medium : Capacity To Ship Packages Within D days (0) | 2022.11.15 |
leetcode medium : Range Sum Query Mutable (1) | 2022.11.15 |
leetcode hard : Height of Binary Tree After Subtree Removal Queries (0) | 2022.11.04 |