trie中文名又叫做字典樹,字首樹等,因為其結構獨有的特點,經常被用來統計,排序,和儲存大量的字串,經常見於搜尋提示,輸入法文字關聯等,當輸入乙個值,可以自動搜尋出可能的選擇。當沒有完全匹配的結果時,可以返回字首最為相似的可能。
基本性質:
1.根節點不含有字元,其餘各節點有且只有乙個字元。
2.根節點到某一節點中經過的節點儲存的值連線起來就是對應的字串。
3.每乙個節點所有的子節點的值都不應該相同。
借用一下維基百科上的一張:
看圖還是蠻好理解的。但是我們應該怎麼操作呢。
應為英文有26個字母,所以每個單詞的每個位置都可能有26種取法,因此,我們可以為每個節點去26個子節點:
裡面有個很逗比的事情,我覺得可能是源**編寫人員犯錯誤。我們知道 arrays.copyofrange 有乙個from和to的形參,意思是從索引為from開始複製,到索引to 結束,但是,看原始碼,我們可以看到它複製的內容長度是:to - from;當我們需要拷貝 0到 5的內容時,需要拷貝6個值,但計算確實5,很明顯少了乙個,所以,我們編碼是需要注意一下。 其餘看**應該都懂的。public class trienode
public static void addnode(trienode root, char words)
int index = words[0] - 'a';
if (root.childnodes[index] == null)
root.childnodes[index].freg++;
words = arrays.copyofrange(words, 1, words.length);
if (checkwordslenght(words))
addnode(root.childnodes[index], words);
}public static void deletenode(trienode root, char words)
int index = words[0] - 'a';
if (root.childnodes[index] == null)
root.childnodes[index].freg--;
if (root.childnodes[index].freg == 0)
words = arrays.copyofrange(words, 1, words.length);
if (checkwordslenght(words))
deletenode(root.childnodes[index], words);
}public static int getcountofwords(trienode root, char words)
int index = words[0] - 'a';
if (root.childnodes[index] == null)
words = arrays.copyofrange(words, 1, words.length);
if (checkwordslenght(words))
return getcountofwords(root.childnodes[index], words);}}
Trie 字典樹 字首樹
所有的php檔案放到同乙個目錄下 trie charmap.php map.php stdmap.php trie.php trienode.php index.php test.php words.txt trienode.php class trienode 字典樹是利用字串的公共字首來節約儲存...
Trie 字典樹 字首樹
目錄trie是乙個多叉樹,trie專門為處理字串而設計的。使用我們之前實現的二分搜尋樹來查詢字典中的單詞,查詢的時間複雜度為o logn 如果有100萬 220 個單詞,則logn大約等於20,但是使用trie這種資料結構,查詢每個條目的時間複雜度,和一共有多少個條目無關!時間複雜度為o w w為被...
Trie樹,字典樹,字首樹
trie樹,字典樹,字首樹,都是同一顆樹,雜湊樹的變種題目鏈結 常用於文字的詞頻統計 它的特點就是,空間占用小,查詢快 它的儲存方式如下圖所示 對於從樹的根節點走到每乙個黑色節點所經過的路徑,如果將路徑上的字母都連起來的話,就都對應著詞典中的乙個單詞 trie樹,分別有插入,查詢和刪除3種操作,插入...