leetcode 211. Design Add and Search Words Data Structure(python)

1,344 阅读4分钟

「这是我参与2022首次更文挑战的第17天,活动详情查看:2022首次更文挑战

描述

Design a data structure that supports adding new words and finding if a string matches any previously added string.

Implement the WordDictionary class:

  • WordDictionary() Initializes the object.
  • void addWord(word) Adds word to the data structure, it can be matched later.
  • bool search(word) Returns true if there is any string in the data structure that matches word or false otherwise. word may contain dots '.' where dots can be matched with any letter.

Example 1:

Input
["WordDictionary","addWord","addWord","addWord","search","search","search","search"]
[[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]]
Output
[null,null,null,null,false,true,true,true]

Explanation
WordDictionary wordDictionary = new WordDictionary();
wordDictionary.addWord("bad");
wordDictionary.addWord("dad");
wordDictionary.addWord("mad");
wordDictionary.search("pad"); // return False
wordDictionary.search("bad"); // return True
wordDictionary.search(".ad"); // return True
wordDictionary.search("b.."); // return True

Note:

1 <= word.length <= 500
word in addWord consists lower-case English letters.
word in search consist of  '.' or lower-case English letters.
At most 50000 calls will be made to addWord and search.

解析

根据题意,设计一个数据结构,支持添加新单词并查找字符串是否与任何先前添加的字符串匹配。

实现 WordDictionary 类:

  • WordDictionary() 初始化对象
  • void addWord(word) 将 word 添加到数据结构中,以后可以用于匹配
  • bool search(word) 如果数据结构中存在任何与 word 匹配的字符串,则返回 true,否则返回 false。 单词可能包含点 '.' ,其中点可以与任何字母匹配

其实这道题如果用 python 的内置正则模块 re.search ,很容易就做出来了,我们只需要把所有要加的字符串都拼接到全局变量 s 中,但是需要注意的是我们对于每个单词之间都用到了一个分隔符 & 来分隔插入的 word ,用其他的符号也是可以的,只要不是 . 就行。然后我们在 search 函数中将 word 左右两边各加一个 & 来拼接成一个 pattern ,这样我们利用 re.search 函数在 s 中进行正则搜索即可,只要 result 有结果说明就是 True ,否则就是 False 。

解答

class WordDictionary(object):
    
    def __init__(self):
        self.s = '&'

    def addWord(self, word):
        """
        :type word: str
        :rtype: None
        """
        self.s += word + '&'
        
    def search(self, word):
        """
        :type word: str
        :rtype: bool
        """
        pattern = '&' + word + '&'
        result = re.search(pattern, self.s)
        return True if result else False
        
        
          	      
		

运行结果

Runtime: 2048 ms, faster than 5.10% of Python online submissions for Design Add and Search Words Data Structure.
Memory Usage: 24.2 MB, less than 95.07% of Python online submissions for Design Add and Search Words Data Structure.

解析

其实上面的解答还是很取巧的,毕竟用到了内置函数,尽管可以通过,但是没什么技术含量,我们还是对于题目要考察的内容进行一下梳理。

其实这道题目一开始就是初始化出一种数据结果,这种数据结构既能够将所有的单词 word 都插入保存,并且还支持单词的匹配功能,这里的匹配分为两种情况第一种就是完全由小写字母组成的单词,这种单词最好进行匹配,只要挨个对应字母就可以知道有没有匹配结果,但是另外一种还夹杂着 . 的单词进行匹配有点难度,只要碰到 . 我们就只能在该位置上出现的所有的字母都进行考虑,这明显是需要一个 Trie 树来保存和搜索。

我们只需要将所有的单词的每个字符都插入到 Trie 中,然后用一个布尔变量 isWord 来表示是否是一个单词,当我们用 search 来查找 word 的时候,只需要沿着 root 向下查找节点,分两种情况,当前字符为 . 的时候遍历其后面所有的子节点,如果不是字母,那么就直接找该字母的子节点即可,递归结束条件就是当单词为空且当前节点 isWord 为 True 的时候,

解答

class TrieNode():
    def __init__(self):
        self.children = defaultdict(TrieNode)
        self.isWord = False

class WordDictionary(object):
    
    def __init__(self):
        self.root = TrieNode()

    def addWord(self, word):
        """
        :type word: str
        :rtype: None
        """
        node = self.root
        for c in word:
            node = node.children[c]
        node.isWord = True

    def search(self, word):
        """
        :type word: str
        :rtype: bool
        """
        node = self.root
        self.result = False

        def dfs(node, word):
            if not word:
                if node.isWord:
                    self.result = True
                return
            if word[0] == ".":
                for n in node.children.values():
                    dfs(n, word[1:])
            else:
                node = node.children.get(word[0])
                if not node:
                    return
                dfs(node, word[1:])

        dfs(node, word)
        return self.result

运行结果

Runtime: 376 ms, faster than 62.92% of Python online submissions for Design Add and Search Words Data Structure.
Memory Usage: 38.3 MB, less than 6.46% of Python online submissions for Design Add and Search Words Data Structure.

原题链接

leetcode.com/problems/de…

您的支持是我最大的动力