1. 程式人生 > >208 Implement Trie (Prefix Tree)

208 Implement Trie (Prefix Tree)

題目:

Implement a trie with insert, search, and startsWith methods.

Note:
You may assume that all inputs are consist of lowercase letters a-z.

解題思路:
這道題的考點是設計字首樹
一開始並不知道什麼是字首樹,所以無法下手解決。

Trie樹,又稱為字典樹、單詞查詢樹或者字首樹,是一種用於快速檢索的多叉數結構。例如,英文字母的字典樹是26叉數,數字的字典樹是10叉樹。
Trie樹的基本性質有三點,歸納為:
1. 根節點不包含字元,根節點外每一個節點都只包含一個字元。
2. 從根節點到某一節點,路徑上經過的字元連線起來,為該節點對應的字串。
3. 每個節點的所有子節點包含的字串不相同。

使用 HashMap

class TrieNode {
    // Initialize your data structure here.
    char c;
    HashMap<Character, TrieNode> children = new HashMap();
    boolean isLeaf;

    public TrieNode() {}

    public TrieNode(char c) {
        this.c = c;
    }
}

public class Trie {
    private TrieNode root;

    public
Trie() { root = new TrieNode(); } // Inserts a word into the trie. public void insert(String word) { HashMap<Character, TrieNode> children = root.children; for(int i = 0; i < word.length(); i ++) { char c = word.charAt(i); TrieNode t; if
(children.containsKey(c)) { t = children.get(c); } else { t = new TrieNode(c); children.put(c, t); } children = t.children; if(i == word.length() - 1) t.isLeaf = true; } } // Returns if the word is in the trie. public boolean search(String word) { TrieNode t = searchNode(word); if(t != null && t.isLeaf == true ) return true; else return false; } // Returns if there is any word in the trie // that starts with the given prefix. public boolean startsWith(String prefix) { if(searchNode(prefix) == null) return false; else return true; } public TrieNode searchNode(String word) { HashMap<Character, TrieNode> children = root.children; TrieNode t = null; for(int i = 0; i < word.length(); i ++) { char c = word.charAt(i); if(children.containsKey(c)) { t = children.get(c); } else { return null; } children = t.children; } return t; } } // Your Trie object will be instantiated and called as such: // Trie trie = new Trie(); // trie.insert("somestring"); // trie.search("key");
14 / 14 test cases passed.
Status: Accepted
Runtime: 52 ms