標籤:
題目:
Implement a trie with insert, search, and startsWith methods.
// Your Trie object will be instantiated and called as such:
// Trie trie = new Trie();
// trie.insert("somestring");
// trie.search("key");
思路:
題目的內容是實現一個首碼樹,用來儲存string的,因此可以理解為一個26叉樹,為了儲存每一個節點的孩子,用hashmap來進行儲存。
同時回顧首碼樹的概念,除了內容為一個字元外,每一個節點還應有一個標誌位,是否為已經查過的(即添加的)單詞。
insert:分析單詞的每一個字元,如果存在與已經有的孩子中,則迴圈轉到該孩子節點,否則建立孩子節點,最後在單詞的末尾字元isWord標誌位true;
search: 逐個分析每個字元,如果不存在該字元的孩子則返回false,否則迴圈之後,查看末尾字元的標誌位即可;
pifix: 和search一樣,只是在最後只要是都存在每個字元相應的孩子map,則返回true。
代碼:
class TrieNode { // Initialize your data structure here. boolean isWord; HashMap<Character, TrieNode> map; public TrieNode() { map = new HashMap<Character, TrieNode>(); }}public class Trie { private TrieNode root; public Trie() { root = new TrieNode(); } // Inserts a word into the trie. public void insert(String word) { char[] charray = word.toCharArray(); TrieNode temp = root; for(int i = 0 ; i < charray.length ; i++){ if(!temp.map.containsKey(charray[i])) temp.map.put(charray[i], new TrieNode()); //添加 temp = temp.map.get(charray[i]); //轉到孩子節點 if(i == charray.length - 1) //末尾字元 temp.isWord = true; } } // Returns if the word is in the trie. public boolean search(String word) { TrieNode temp = root; for(int i = 0 ; i < word.length() ; i++){ TrieNode next = temp.map.get(word.charAt(i)); if(next == null) return false; temp = next; } return temp.isWord; } // Returns if there is any word in the trie // that starts with the given prefix. public boolean startsWith(String prefix) { TrieNode temp = root; for(int i = 0 ; i < prefix.length() ; i++){ TrieNode next = temp.map.get(prefix.charAt(i)); if(next == null) return false; temp = next; } return true; }}
參考連結:http://www.bubuko.com/infodetail-807921.html
[LeetCode-JAVA] Implement Trie (Prefix Tree)