zoukankan      html  css  js  c++  java
  • 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)
  • 相关阅读:
    源码分析
    HR不会告诉你的秘密
    文档生产工具 Doxygen
    Win7设置共享文件夹
    ZigBee NV层使用
    ZigBee2006,2007,pro各个版本的区别
    第一百九十三节,jQuery EasyUI,Draggable(拖动)组件
    第一百九十二节,jQuery EasyUI 使用
    第一百九十一节,jQuery EasyUI 入门
    第一百九十节,jQuery,编辑器插件
  • 原文地址:https://www.cnblogs.com/zhuozige/p/12871422.html
Copyright © 2011-2022 走看看