Problem Solving/LeetCode
2023.03.19 Today's Challenge
fabichoi
2023. 3. 19. 23:45
https://leetcode.com/problems/design-add-and-search-words-data-structure/
Design Add and Search Words Data Structure - LeetCode
Can you solve this real interview question? Design Add and Search Words Data Structure - Design a data structure that supports adding new words and finding if a string matches any previously added string. Implement the WordDictionary class: * WordDictionar
leetcode.com
class WordDictionary:
def __init__(self):
self.children = [None] * 26
self.is_complete = False
def addWord(self, word: str) -> None:
curr = self
for c in word:
if curr.children[ord(c) - ord('a')] == None:
curr.children[ord(c) - ord('a')] = WordDictionary()
curr = curr.children[ord(c) - ord('a')]
curr.is_complete = True
def search(self, word: str) -> bool:
curr = self
for i in range(len(word)):
c = word[i]
if c == '.':
for ch in curr.children:
if ch != None and ch.search(word[i+1:]):
return True
return False
if curr.children[ord(c) - ord('a')] == None:
return False
curr = curr.children[ord(c) - ord('a')]
return curr != None and curr.is_complete
반응형