/**
 * Your Trie object will be instantiated and called as such:
 * Trie trie = new Trie();
 * trie.insert("lintcode");
 * trie.search("lint"); will return false
 * trie.startsWith("lint"); will return true
 */
class TrieNode {
    // Initialize your data structure here.
    boolean isWord;
    public TrieNode[] child = new TrieNode[26];;
    public TrieNode() {

    }
}

public class Trie {
    private TrieNode root;

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

    // Inserts a word into the trie.
    public void insert(String word) {
        TrieNode ws = root;
        for (char c : word.toCharArray()) {
            if (ws.child[c - 'a'] == null) {
                ws.child[c - 'a'] = new TrieNode();
            }
            ws = ws.child[c - 'a'];
        }
        ws.isWord = true;
    }

    // Returns if the word is in the trie.
    public boolean search(String word) {
        TrieNode ws = root;
        for (char c : word.toCharArray()) {
            if (ws.child[c - 'a'] == null) {
               return false;
            }
            ws = ws.child[c - 'a'];
        }
        return ws.isWord;
    }

    // Returns if there is any word in the trie
    // that starts with the given prefix.
    public boolean startsWith(String prefix) {
         TrieNode ws = root;
        for (char c : prefix.toCharArray()) {
            if (ws.child[c - 'a'] == null) {
               return false;
            }
            ws = ws.child[c - 'a'];
        }
        return true;
    }
}

results matching ""

    No results matching ""