Trie树

class Trie {

    private Node root;

    /** Initialize your data structure here. */
    public Trie() {
        this.root = new Node();
    }
    
    /** Inserts a word into the trie. */
    public void insert(String word) {
        Node p = root;
        for (int i = 0; i < word.length(); i++) {
            int dif = word.charAt(i) - 'a';
            if (p.son[dif] == null) {
                p.son[dif] = new Node();
            }
            p = p.son[dif];
        }
        p.isEnd = true;
    }
    
    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        Node p = root;
        for (int i = 0; i < word.length(); i++) {
            int dif = word.charAt(i) - 'a';
            if (p.son[dif] == null) {
                return false;
            } else {
                p = p.son[dif];
            }
        }

        return p.isEnd;
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        Node p = root;
        for (int i = 0; i < prefix.length(); i++) {
            int dif = prefix.charAt(i) - 'a';
            if (p.son[dif] == null) {
                return false;
            } else {
                p = p.son[dif];
            }
        }

        return p != null;
    }



    static class Node {
        boolean isEnd;
        Node[] son = new Node[26];
    }
}

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

你可能感兴趣的:(数据结构与算法)