class Trie {
    private TrieNode root;

    class TrieNode {
        TrieNode[] children = new TrieNode[26];
        boolean isWord;
    }
    /** Initialize your data structure here. */
    public Trie() {
        root = new TrieNode();
    }
    
    /** Inserts a word into the trie. */
    public void insert(String word) {
        TrieNode runner = root;
        for (char c : word.toCharArray()) {
            if (runner.children[(int)(c - 'a')] == null) {
                runner.children[(int)(c - 'a')] = new TrieNode();
            }
            runner = runner.children[(int)(c - 'a')];
        }
        runner.isWord = true;
    }
    
    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        TrieNode runner = root;
        for (char c : word.toCharArray()) {
            if (runner.children[(int)(c - 'a')] == null) {
                return false;
            }
            runner = runner.children[(int)(c - 'a')];
        }
        return runner.isWord;
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        TrieNode runner = root;
        for (char c : prefix.toCharArray()) {
            if (runner.children[(int)(c - 'a')] == null) {
                return false;
            }
            runner = runner.children[(int)(c - 'a')];
        }
        
        return isWords(runner);
    }
    
    private boolean isWords(TrieNode node) {
        if (node == null) {
            return false;
        }
        
        if (node.isWord) {
            return true;
        }
        
        for (TrieNode child : node.children) {
            if (isWords(child)) {
                return true;
            }
        }
        return false;
    }
}

/**
 * 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);
 */

 

posted on 2017-08-28 12:24  keepshuatishuati  阅读(94)  评论(0编辑  收藏  举报