211. 添加與搜索單詞 - 數據結構設計 難度 中等

設計一個支持以下兩種操作的數據結構:

void addWord(word)
bool search(word)

search(word) 可以搜索文字或正則表達式字符串,字符串只包含字母 . 或 a-z 。 . 可以表示任何一個字母。

示例:

addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true

說明:

你可以假設所有單詞都是由小寫字母 a-z 組成的。

 

這道理兩種做法,字典樹或者前綴樹。但是由於題目是考察前綴樹的,所以字典樹的時間效率很差。

字典樹

class WordDictionary(object):

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.root = {}


    def addWord(self, word):
        """
        Adds a word into the data structure.
        :type word: str
        :rtype: None
        """
        tmp = self.root
        for i in word:
            if i not in tmp:
                tmp[i] = {}
            tmp = tmp[i]
        tmp['end'] = True


    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 check(word, tmp):
            if word == '':
                if 'end' in tmp:
                    return True
                return False
            elif 'end' in tmp and len(tmp)==1:
                return False
            
            if word[0] in tmp and check(word[1:], tmp[word[0]]):
                return True
            if word[0] == '.':
                for i in tmp:
                    if i != 'end' and check(word[1:], tmp[i]):
                        return True
            return False
        return check(word, self.root)

前綴樹

class WordDictionary(object):

    def __init__(self):
        """
        Initialize your data structure here.
        """
        from collections import defaultdict
        self.word_dict = defaultdict(list)
        

    def addWord(self, word):
        """
        Adds a word into the data structure.
        :type word: str
        :rtype: void
        """
        self.word_dict[len(word)].append(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
        """
        for item in self.word_dict[len(word)]:
            flag = False
            for x,y in zip(item,word):
                if y == "." or x == y:
                    continue
                else:
                    flag = True
                    break
            if not flag :
                return True
        return False

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章