python beat 95%, using map, very straightforward


  • 0
    L

    The key idea is to store {len: [dicts]} of input dict. very simple.

    class MagicDictionary(object):
    
        def __init__(self):
            """
            Initialize your data structure here.
            """
            self.m = {}
            
    
        def buildDict(self, dict):
            """
            Build a dictionary through a list of words
            :type dict: List[str]
            :rtype: void
            """
            if not dict:
                return
            for word in dict:
                l = len(word)
                v = self.m.get(l, set())
                v.add(word)
                self.m[l] = v
            
    
        def search(self, word):
            """
            Returns if there is any word in the trie that equals to the given word after modifying exactly one character
            :type word: str
            :rtype: bool
            """
            if not word:
                return False
            l = len(word)
            if l not in self.m:
                return False
            values = self.m[l]
            for val in values:
                diff = 0
                for i in range(l):
                    if val[i] != word[i]:
                        diff += 1
                        if diff > 1:
                            break
                if diff == 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.