字首樹python實現

2021-09-24 20:12:07 字數 1588 閱讀 9839

#file name : 字首樹.py

class trienode(object):

def __init__(self):

self.path = 0

#路過此節點幾個

self.end = 0

#以此為結尾的幾個

self.map = [none for i in range(26)]

#每乙個節點有26條路

class trie(object):

def __init__(self):

self.root = trienode()

def insert(self,word):

if word == none:

return

node = self.root

for i in word:

index = ord(i) - ord('a')

#ord 為阿斯科碼

if node.map[index] == none:

node.map[index] = trienode()

node = node.map[index]

node.path += 1

node.end+=1

print('insert successful !!!')

def search(self,word):

if word == none:

return 0

node = self.root

for i in word:

index = ord(i)-ord('a')

if node.map[index]==none:

return 0

node = node.map[index]

return node.end

# 如何區分 『be』 ,『bef』

# 返回插入幾次

def delete(self,word):

if self.search(word) != 0:

node = self.root

for i in word:

index = ord(i)-ord('a')

node.map[index].path -=1

if node.map[index].path==0:

#本來原來就有乙個 再刪乙個 就沒了

#變成0 代表不需要此節點了

node.map[index] = none

return

node = node.map[index]

node.end-=1

# 不要把字母放到節點上

def prefixnumber(self,pre):

if pre == none:

return

node = self.root

for i in pre:

index = ord(i)-ord('a')

if node.map[index] == none:

return 0

node = node.map[index]

return node.path

字首樹 java實現)

package class 07 字首樹 例子 乙個字串型別的陣列arr1,另乙個字串型別的陣列arr2。arr2中有哪些字元,是arr1中出現的?請列印 arr2中有哪些字元,是作為arr1中某個字串字首出現的?請列印 arr2中有哪些字元,是作為arr1中某個字串字首出現的?請列印arr2中出現...

Trie字首樹簡單實現

trie樹,字首樹,字典樹,又稱單詞查詢樹或鍵樹,是一種樹形結構。典型應用是用於統計和排序大量的字串 但不僅限於字串 可以用於搜尋引擎系統,用於文字詞頻統計。trie利用字串的公共字首來避免無謂的查詢,從而降低查詢時間的開銷以達到提高效率的目的。1.根節點不包含字元,除根節點外每乙個節點都只包含乙個...

字首樹的簡單實現

1.字首樹 字首樹又稱為單詞查詢樹,是一種樹形的結構,用於儲存大量的字串,它的優點是 利用字串的公共字首來節約儲存空間 trie樹主要是利用詞的公共字首縮小查詞範圍 通過狀態間的對映關係避免了字元的遍歷,從而達到高效檢索的目的 2.可以先宣告乙個節點trienode,節點包括以下幾個屬性 trien...