• Leetcode练习(Python):回溯算法类:第211题:添加与搜索单词


    题目:
    添加与搜索单词 - 数据结构设计:设计一个支持以下两种操作的数据结构:  void addWord(word) bool search(word) search(word) 可以搜索文字或正则表达式字符串,字符串只包含字母 . 或 a-z 。 . 可以表示任何一个字母。 
    思路:
    尝试了很长时间的回溯方式,但是一直无法出来结果。第一感觉是不用回溯,直接使用比较的方式来做,程序1使用的是常规方法,之后补充回溯方法的程序。
    程序1:常规方法
    class WordDictionary:
        def __init__(self):
            """
            Initialize your data structure here.
            """
            self.myDict = {}
    
        def addWord(self, word: str) -> None:
            """
            Adds a word into the data structure.
            """
            length = len(word)
            if length in self.myDict:
                self.myDict[length] += [word]
            else:
                self.myDict[length] = [word]
                
        def search(self, word: str) -> bool:
            """
            Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
            """
            length = len(word)
            if length in self.myDict:
                for auxiliary in self.myDict[length]:
                    index = 0
                    for index1 in range(length):
                        if word[index1] != auxiliary[index1] and word[index1] != '.':
                            break
                        elif word[index1] == auxiliary[index1] or word[index1] == '.':
                            index += 1
                    if index == length:
                        return True
            if length not in self.myDict:
                return False
            return False
    
    # Your WordDictionary object will be instantiated and called as such:
    # obj = WordDictionary()
    # obj.addWord(word)
    # param_2 = obj.search(word)
  • 相关阅读:
    【Rust】结构体 struct
    【Rust】所有权、引用、借用
    Centos7升级glibc2.24
    ES用户权限控制
    PHP压缩html网页代码 : 清除空格,制表符,注释标记
    PHP通过HTTP_USER_AGENT判断是否为手机移动终端的函数
    php正则表达式替换URL链接地址为指定url的形式
    PHP下使用CURL方式POST数据至API接口的方法
    设计模式代理模式
    设计模式生成器模式
  • 原文地址:https://www.cnblogs.com/zhuozige/p/12871422.html
Copyright © 2020-2023  润新知