Design a data structure that supports the following two operations:
void addWord(word) bool search(word)
search(word) can search a literal word or a regular string containing only letters a-z or .. A . means it can represent any one letter.
Example:
addWord(\"bad\") addWord(\"dad\") addWord(\"mad\") search(\"pad\") -> false search(\"bad\") -> true search(\".ad\") -> true search(\"b..\") -> true
Note:
You may assume that all words are consist of lowercase letters a-z.
Answer:
Trie Answer:
class WordDictionary( ):
def __init__(self):
\"\"\"
Initialize your data structure here.
\"\"\"
self.next={}
self.finish=False
def addWord(self, word):
\"\"\"
Adds a word into the data structure.
:type word: str
:rtype: void
\"\"\"
node=self
for c in word:
if node.next.has_key(c):
node=node.next[c]
else:
newnode=WordDictionary()
node.next[c]=newnode
node=node.next[c]
node.finish=True
def search(self, word):
\"\"\"
Returns if the word is in the data structure. A word could contain the dot character \'.\' to represent any one letter.
:type word: str
:rtype: bool
\"\"\"
node=self
i=0
l=len(word)
while i<l:
c=word[i]
if c==\".\":
for tmpnode in node.next.values():
if tmpnode.search(word[i+1:]):
return True
return False
else:
if node.next.has_key(c):
node=node.next[c]
else:
return False
i+=1
if node.finish:
return True
return False
# Your WordDictionary will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word)
有点慢
学习bbbarely的算法
from collections import defaultdict
class WordDictionary( ):
def __init__(self):
\"\"\"
Initialize your data structure here.
\"\"\"
self.dict=defaultdict(set)
def addWord(self, word):
\"\"\"
Adds a word into the data structure.
:type word: str
:rtype: void
\"\"\"
w_len=len(word)
self.dict[w_len].add(word)
def search(self, word):
\"\"\"
Returns if the word is in the data structure. A word could contain the dot character \'.\' to represent any one letter.
:type word: str
:rtype: bool
\"\"\"
w_len=len(word)
tmpset=self.dict[w_len]
if not tmpset:
return False
if word in tmpset:
return True
for i in range(w_len):
c=word[i]
if c!=\".\":
tmpset={w for w in tmpset if w[i]==c}
if not tmpset:
return False
return True
# Your WordDictionary will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word)
根据长度把词存入dict中
继续阅读与本文标签相同的文章
上一篇 :
强生医疗与天智航签署商业和研发合作
下一篇 :
十年磨一剑,自研的ParaStor到底有什么好?
-
PostgreSQL系统隐藏字段
2026-05-18栏目: 教程
-
7月24日阿里云峰会.上海 开发者大会回看
2026-05-18栏目: 教程
-
aPaaS平台是什么?aPaaS与PaaS有什么区别?
2026-05-18栏目: 教程
-
【从入门到放弃-ZooKeeper】ZooKeeper实战-分布式队列 | 9月18号栖夜读
2026-05-18栏目: 教程
-
Docker日志收集最佳实践
2026-05-18栏目: 教程
