算法中trie怎么实现
Trie 的定义
Trie(发音为“try”),又名前缀树或字典树,是一种有序树,是一种专门处理字符串匹配的数据结构。它的优势在于,查询某个字符串是否为某个文本串的子串时,只需要进行一次遍历,就可以得到结果。
Trie 的实现原理
Trie 树是一种多叉树,其每个节点有多个子节点,每个节点都有一个字符,这个字符指的是从根结点到该节点组成的字符串。Trie 树的根结点不包含字符,除根结点外每一个节点都只包含一个字符。每个节点的所有子节点包含的字符都不相同。
Trie 的实现方法
Trie 树的实现一般是用数组或者链表实现,用数组实现 Trie 树,每个节点的孩子节点用一个长度为 26 的数组来表示,其中每个元素代表一个字符,数组的下标代表字符的顺序,比如字符 'a' 对应下标 0,字符 'b' 对应下标 1,以此类推。
Trie 的实现代码
class TrieNode:
def __init__(self):
self.children = [None] * 26
self.isEndOfWord = False
class Trie:
def __init__(self):
self.root = self.getNode()
def getNode(self):
return TrieNode()
def _charToIndex(self,ch):
return ord(ch) - ord('a')
def insert(self,key):
pCrawl = self.root
length = len(key)
for level in range(length):
index = self._charToIndex(key[level])
if not pCrawl.children[index]:
pCrawl.children[index] = self.getNode()
pCrawl = pCrawl.children[index]
pCrawl.isEndOfWord = True
def search(self, key):
pCrawl = self.root
length = len(key)
for level in range(length):
index = self._charToIndex(key[level])
if not pCrawl.children[index]:
return False
pCrawl = pCrawl.children[index]
return pCrawl != None and pCrawl.isEndOfWord
猜您想看
-
Oedax的原理和应用是什么
Oedax(O...
2023年04月28日 -
如何使用iPhone上的新闻查询工具及时获取社会新闻
如何使用iPh...
2023年05月05日 -
网站建设中怎么辨别非自然链接
一、网站链接的...
2023年05月26日 -
大数据云迁移五大要点
一、云迁移的重...
2023年05月22日 -
怎样理解gnomAD数据库
gnomAD(...
2023年07月21日 -
在CS:GO游戏中玩家间如何互相帮助?
《CS:GO》...
2023年04月17日