208. 實現 Trie (前綴樹) 還沒ok


實現一個 Trie (前綴樹),包含 insert, search, 和 startsWith 這三個操作。

示例:

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
說明:

你可以假設所有的輸入都是由小寫字母 a-z 構成的。
保證所有輸入均爲非空字符串。
class Trie {

    /** Initialize your data structure here. */
    private class Node{
        //childs 存放着指向各個孩子結點的指針。
        Node[] childs = new Node[26];
        boolean isLeaf;
    }

    private Node root = new Node();

    public Trie() {
    }

    /** Inserts a word into the trie. */
    public void insert(String word) {
        insert(word,root);
    }

    private void insert(String word,Node node){
        if(node == null) return ;
        if(word.length() == 0){
            node.isLeaf = true;
            return ;
        }
        int index = indexForChar(word.charAt(0));
        if(node.childs[index] == null){
            node.childs[index] = new Node();
        }
        insert(word.substring(1),node.childs[index]);
    }
    private int indexForChar(char c){
        return c - 'a';
    }

    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        return search(word,root);
    }
    private boolean search(String word,Node node){
        if(node == null) return false;
        if(word.length() == 0) return node.isLeaf;
        int index = indexForChar(word.charAt(0));
        return search(word.substring(1),node.childs[index]);
    }

    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        return startWith(prefix,root);
    }
    private boolean startWith(String prefix,Node node){
        if(node == null) return false;
        if(prefix.length() == 0) return true;//注意這裏
        int index = indexForChar(prefix.charAt(0));
        return startWith(prefix.substring(1),node.childs[index]);
    }
}

/**
 * Your Trie object will be instantiated and called as such:
 * Trie obj = new Trie();
 * obj.insert(word);
 * boolean param_2 = obj.search(word);
 * boolean param_3 = obj.startsWith(prefix);
 */

參考:https://blog.csdn.net/wsyw126/article/details/61416055

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章