Leetcode练习(Python):回溯算法类:第211题:添加与搜索单词 - 数据结构设计:设计一个支持以下两种操作的数据结构: void addWord(word) bool search(word) search(word) 可以搜索文字或正则表达式字符串,字符串只包含字母 . 或 a-z 。 . 可以表示任何一个字母。
题目:
添加与搜索单词 - 数据结构设计:设计一个支持以下两种操作的数据结构: 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)
浙公网安备 33010602011771号