Implement a trie withinsert,search, andstartsWithmethods.

class Trie {
    class Node {
        //public char c;
        public Node[] children;
        public boolean isLeaf;

        public Node() {
            this.children = new Node[26];
        }
    }

    private Node root;

    /** Initialize your data structure here. */
    public Trie() {
        root = new Node();
    }

    /** Inserts a word into the trie. */
    public void insert(String word) {
        Node temp = root;
        for(int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);

            if(temp.children[c - 'a'] == null) {
                temp.children[c - 'a'] = new Node();
            }
            temp = temp.children[c - 'a'];
        }
        temp.isLeaf = true;
    }

    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        if(word == null || word.length() == 0)
            return true;

        Node temp = root;
        for(int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);

            if(temp.children[c - 'a'] == null)
                return false;
            temp = temp.children[c - 'a'];
        }

        return temp.isLeaf;
    }

    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        if(prefix == null || prefix.length() == 0)
            return true;

        Node temp = root;
        for(int i = 0; i < prefix.length(); i++) {
            char c = prefix.charAt(i);

            if(temp.children[c - 'a'] == null)
                return false;
            temp = temp.children[c - 'a'];
        }
        return true;
    }
}

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

results matching ""

    No results matching ""