[LeetCode] 211. Design Add and Search Words Data Structure

김민우·2023년 3월 19일
0

알고리즘

목록 보기
159/189

- Problem

211. Design Add and Search Words Data Structure


- 내 풀이 (Trie, DFS)

class TrieNode:
    def __init__(self):
        self.child = {}
        self.is_word = False

class WordDictionary:
    def __init__(self):
        self.root = TrieNode()

    def addWord(self, word):
        cur = self.root
        for c in word:
            if c not in cur.child :
                cur.child[c] = TrieNode()
            cur = cur.child[c]
        cur.is_word = True

    def search(self, word):
        return self.dfs(word, self.root)

    def dfs(self, word, node):
        if not word:
            return node.is_word

        if word[0] == ".":
            return any(self.dfs(word[1:], child_node) for child_node in node.child.values())
            
        else:
            if word[0] in node.child:
                return self.dfs(word[1:], node.child[word[0]])

- 결과

profile
Pay it forward.

0개의 댓글