189ms Python AC solution (non-Pythonic) using dict and set


  • 0
    W
    class WordDictionary(object):
    
        def __init__(self):
            """
            Initialize your data structure here.
            """
            self.d = {}
    
        def addWord(self, word):
            """
            Adds a word into the data structure.
            :type word: str
            :rtype: void
            """
            if len(word) not in self.d:
                self.d[len(word)] = set(word)
            else:
                self.d[len(word)].add(word)
    
        def search(self, word):
            """
            Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
            :type word: str
            :rtype: bool
            """
            if not word or len(word) not in self.d: return False
            if '.' not in word: return word in self.d[len(word)]
            for v in self.d[len(word)]:
                for i in xrange(len(word)):
                    if '.'!=word[i] and word[i]!=v[i]: break
                    if i==len(word)-1: return True
            return False
    

Log in to reply
 

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