파비의 매일매일 공부기록

2023.03.19 Today's Challenge 본문

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
반응형

'Problem Solving > LeetCode' 카테고리의 다른 글

2023.03.21 Today's Challenge  (0) 2023.03.21
2023.03.20 Today's Challenge  (0) 2023.03.20
2023.03.18 Today's Challenge  (0) 2023.03.18
2023.03.17 Today's Challenge  (0) 2023.03.17
2023.03.16 Today's Challenge  (0) 2023.03.16
Comments