Trie

Your Trie object will be instantiated and called as such:

Trie trie = new Trie();
trie.insert("somestring");
trie.search("key");

  • Time: O(n)
  • Space: O(1)
// Implement a trie with insert, search, and startsWith methods.
class TrieNode {
    boolean isWord;
    TrieNode[] childs = new TrieNode[26];

    // Initialize your data structure here.
    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 node = root;
        for (int i = 0; i < word.length(); i++) {
            if (node.childs[word.charAt(i) - 'a'] == null) {
                node.childs[word.charAt(i) - 'a'] = new TrieNode();
            }
            node = node.childs[word.charAt(i) - 'a'];
        }
        node.isWord = true;
    }

    // Returns if the word is in the trie.
    public boolean search(String word) {
        TrieNode node = root;
        for (int i = 0; i < word.length(); i++) {
            if (node.childs[word.charAt(i) - 'a'] == null) {
                return false;
            } else {
                node = node.childs[word.charAt(i) - 'a'];
            }
        }
        return node.isWord;
    }

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

results matching ""

    No results matching ""