leetcode第208题,字典树的简单实现,上次数学建模比赛的时候就是用的字典树,对于这种数据结构的原理还是比较了解的,不过当时编程水平堪忧,调试了很久。这次我用python来实现字典树,为了实现后缀,我采用字典,这样可以随着动态绑定,另外字典树最重要的还要加入停止标记,来确保单词在什么位置结束。
实现的时候注意几个细节:
1、插入操作时,如果没有达到单词结尾,则正常加挂节点,同时节点向下传递,如果达到了单词结尾,则要在节点上加入停止标记。每种大情况还分两种小情况,一种是该字母已经在children存在了,只需要标记或者向下传递即可。如果该字母还没有,则需要创建新的子节点加挂上去再做上述操作。
2、查找操作的时候,如果字母在children根本不存在,则说明字母不对应,立刻返回False。向下查找时如果单词结束且遇到了单词停止标记,则说明查找成功。如果单词结束了还没有遇到停止标记,查找失败。
3、实现startwith和search非常相似,不同的是,即使这里单词结束了,但是没有停止标记,也允许返回True。
class TrieNode(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.val = None
self.end = False
self.childern = {}
class Trie(object):
def __init__(self):
self.root = TrieNode()
def insert(self, word):
"""
Inserts a word into the trie.
:type word: str
:rtype: void
"""
node = self.root
n = len(word)
for index,c in enumerate(word):
if index == n-1:
if c not in node.childern:
newNode = TrieNode()
newNode.end = True
node.childern[c] = newNode
else:
node.childern[c].end = True
else:
if c not in node.childern:
newNode = TrieNode()
node.childern[c] = newNode
node = newNode
else:
node = node.childern[c]
def search(self, word):
"""
Returns if the word is in the trie.
:type word: str
:rtype: bool
"""
node = self.root
n = len(word)
for index,c in enumerate(word):
if c in node.childern:
if node.childern[c].end == True and index == n-1:
return True
else:
if index == n-1:
return False
else:
node = node.childern[c]
else:
return False
def startsWith(self, prefix):
"""
Returns if there is any word in the trie
that starts with the given prefix.
:type prefix: str
:rtype: bool
"""
node = self.root
n = len(prefix)
for index,c in enumerate(prefix):
if c in node.childern:
if node.childern[c].end == True and index == n-1:
return True
else:
node = node.childern[c]
else:
return False
return True
# Your Trie object will be instantiated and called as such:
trie = Trie()
trie.insert("somestring")
trie.insert("key")
print trie.search("key")
print trie.search("somestring")
print trie.startsWith("as")