Python Trie Solution

  • 0
    class WordDictionary(object):
        def __init__(self):
            self.trie = {}
        def addWord(self, word):
            node = self.trie
            for c in word:
                node = node.setdefault(c, {})
            node['has_word'] = True
        def search(self, word, node = None):
            if not node: node = self.trie
            if not word: return 'has_word' in node
            children = list(string.ascii_lowercase) if word[0] == '.' else [word[0]]
            for child in children:
                if child in node and[1:], node[child]): return True
            return False

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.