Trie(發音相似 "try")或者說 前綴樹 是一種樹形數據結構,用於高效地存儲和檢索字符串數據集中的鍵。這一數據結構有至關多的應用情景,例如自動補完和拼寫檢查。 請你實現 Trie 類: 一、Trie() 初始化前綴樹對象。 二、void insert(String word) 向前綴樹中插入字符串 word 。 三、boolean search(String word) 若是字符串 word 在前綴樹中,返回 true(即,在檢索以前已經插入);不然,返回 false 。 四、boolean startsWith(String prefix) 若是以前已經插入的字符串 word 的前綴之一爲 prefix ,返回true;不然,返回 false 。
示例:java
輸入 ["Trie", "insert", "search", "search", "startsWith", "insert", "search"] [[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]] 輸出 [null, null, true, false, true, null, true] 解釋 Trie trie = new Trie(); trie.insert("apple"); trie.search("apple"); // 返回 True trie.search("app"); // 返回 False trie.startsWith("app"); // 返回 True trie.insert("app"); trie.search("app"); // 返回 True
一、把單詞拆分紅爲一個一個單詞經過樹形結構的方式進行存儲,而後在最後一個字母能使得這條鏈成爲一個單詞就記錄它爲一個單詞。 二、所以,若isWord=true的話,這條鏈就是一個單詞,反之則不是。
一、存儲樹結構的數據結構算法
package com.bean; public class TrieNode { public boolean isWord;//是不是單詞 public TrieNode[] children;//26個小寫字母 public TrieNode() { isWord = true; children = new TrieNode[26]; } }
二、具體實現增刪改查的代碼數據結構
package com.java; import com.bean.TrieNode; public class Day14_Trie { //根節點,根節點是不存儲任何字母的,從根節點的 //子節點開始存儲 private TrieNode root; public Day14_Trie() { root = new TrieNode(); } //插入字符串 public void insert(String word) { TrieNode current = root; for (int i = 0; i < word.length(); i++) { int index = word.charAt(i) - 'a'; //判斷字符有沒有建立,若是沒有建立就建立 if (current.children[index] == null) { current.children[index] = new TrieNode(); //中間的字符不是完整的單詞 current.children[index].isWord = false; } current = current.children[index]; } //最後一個字符才能構成一個完整的單詞 current.isWord = true; } public boolean search(String word) { TrieNode current = find(word); return current != null && current.isWord; } public boolean startsWith(String prefix) { return find(prefix) != null; } private TrieNode find(String str) { TrieNode current = root; int length = str.length(); for (int i = 0; i < length; i++) { int index = str.charAt(i) - 'a'; if ((current = current.children[index]) == null) return null; } return current; } }