力扣每日一题2021-10-19

添加与搜索单词-数据结构设计

  • 211.添加与搜索单词 - 数据结构设计
    • 题目描述
    • 思路:Trie+BFS


211.添加与搜索单词 - 数据结构设计

题目描述

添加与搜索单词 - 数据结构设计


思路:Trie+BFS

字符串前缀匹配最常见的是用Trie,为完成后’.'的任意匹配,是用bfs算法。
力扣每日一题2021-10-19_第1张图片

class WordDictionary:

    def __init__(self):
        self.trie = dict()


    def addWord(self, word: str) -> None:
        cur = self.trie
        for c in word:
            if c in cur:
                cur = cur[c]
            else:
                cur[c] = {}
                cur = cur[c]
        cur["#"] = {}


    def search(self, word: str) -> bool:
        word += "#"
        bfs = deque([(0, self.trie)])
        while bfs:
            idx, cur = bfs.popleft()
            if idx == len(word):
                return True
            if word[idx] == '.':
                for nxt in cur.values():
                    bfs.append((idx+1, nxt))
            elif word[idx] in cur:
                bfs.append((idx+1, cur[word[idx]]))
        return False



# Your WordDictionary object will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word)

你可能感兴趣的:(leetcode每日一题,leetcode)