Python Solution


  • 0
    class TrieNode:
        def __init__(self, val):
            self.val = val
            self.isword = False
            self.children = {}
            
    class WordDictionary(object):
        def __init__(self):
            self.start = TrieNode(0)
    
        def addWord(self, word):
            p = self.start
            for c in word:
                if c not in p.children:
                    p.children[c] = TrieNode(c)
                p = p.children[c]
            p.isword = True
    
        def search(self, word, p=None):
            if not word:
                if not p:
                    return False
                return p.isword
            if not p:
                p = self.start
            for i in range(len(word)):
                if word[i] == '.':
                    for x in p.children:
                        if self.search(word[i+1:],p.children[x]):
                            return True
                    return False
                if word[i] not in p.children:
                    return False
                p = p.children[word[i]]
            return p.isword

Log in to reply
 

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