211. Add and Search Word - Data structure design

use nested dictionary to represent trie tree

class WordDictionary(object):
    def __init__(self):
        """
        initialize your data structure here.
        """
        #use nested dictionary to represent a trie tree, {letter1:{letter3:{},letter4:{}},letter2:{}}
        self.root={}

    def addWord(self, word):
        """
        Adds a word into the data structure.
        :type word: str
        :rtype: void
        """
        current=self.root
        for letter in word:
            current=current.setdefault(letter,{})
        current[None]=None
        

    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
        """
        def find(word,node):
            if not word:#if None in node indicate the end of a word 
                return None in node
            char,word=word[0],word[1:]
            if char!='.':
                return char in node and find(word,node[char])
            return any(find(word,kid) for kid in node.values() if kid)
        return find(word,self.root)

# Your WordDictionary object will be instantiated and called as such:
# wordDictionary = WordDictionary()
# wordDictionary.addWord("word")
# wordDictionary.search("pattern")
class WordDictionary(object):
    def __init__(self):
        """
        initialize your data structure here.
        """
        #use nested dictionary to represent a trie tree, {letter1:{letter3:{},letter4:{}},letter2:{}}
        self.root={}

    def addWord(self, word):
        """
        Adds a word into the data structure.
        :type word: str
        :rtype: void
        """
        current=self.root
        for letter in word:
            current=current.setdefault(letter,{})
        current['$']=None
        

    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
        """
        nodes = [self.root]
        for char in word + '$':
            nodes = [kid for node in nodes for kid in
                     ([node[char]] if char in node else
                      filter(None, node.values()) if char == '.' else [])]
        return bool(nodes)

# Your WordDictionary object will be instantiated and called as such:
# wordDictionary = WordDictionary()
# wordDictionary.addWord("word")
# wordDictionary.search("pattern")

你可能感兴趣的:(211. Add and Search Word - Data structure design)