[LeetCode]Implement Trie (Prefix Tree)

class TrieNode {
    // Initialize your data structure here.
    TrieNode[] child;
    boolean isWord;
    public TrieNode() {
        child = new TrieNode[26];
        isWord = false;
    }
}

public class Trie {
    private TrieNode root;

    public Trie() {
        root = new TrieNode();
    }

    // Inserts a word into the trie.
    public void insert(String word) {
        insert(word, root);
    }
    public void insert(String word, TrieNode root) {
        if (word.length() == 0) {
            root.isWord = true;
            return;
        }
        char ch = word.charAt(0);
        if (root.child[ch - 'a'] == null) {
            root.child[ch - 'a'] = new TrieNode();
        }
        insert(word.substring(1), root.child[ch - 'a']);
    }

    // Returns if the word is in the trie.
    public boolean search(String word) {
        return search(word, root);
    }
    public boolean search(String word, TrieNode root) {
        if (word.length() == 0) {
            return root.isWord;
        }
        char ch = word.charAt(0);
        if (root.child[ch - 'a'] == null) {
            return false;
        } else {
           return search(word.substring(1), root.child[ch - 'a']);
        }
    }

    // Returns if there is any word in the trie
    // that starts with the given prefix.
    public boolean startsWith(String prefix) {
       return startsWith(prefix, root);
    }
    public boolean startsWith(String prefix, TrieNode root) {
        if (prefix.length() == 0) {
            return true;
        }
        char ch = prefix.charAt(0);
        if (root.child[ch - 'a'] == null) {
            return false;
        } else {
            return startsWith(prefix.substring(1), root.child[ch - 'a']);
        }
    }
}

// Your Trie object will be instantiated and called as such:
// Trie trie = new Trie();
// trie.insert("somestring");
// trie.search("key");

 

posted @ 2015-12-06 12:36  Weizheng_Love_Coding  阅读(125)  评论(0编辑  收藏  举报