Array children
Time O(L) per call Space O(total characters × 26)Node with Node[26] and isWord. walk(s) returns the node at the end of s, or null.
class Trie {
private static class Node {
Node[] next = new Node[26];
boolean isWord;
}
private final Node root = new Node();
public Trie() {}
public void insert(String word) {
Node n = root;
for (char c : word.toCharArray()) {
if (n.next[c - 'a'] == null) n.next[c - 'a'] = new Node();
n = n.next[c - 'a'];
}
n.isWord = true;
}
public boolean search(String word) {
Node n = walk(word);
return n != null && n.isWord;
}
public boolean startsWith(String prefix) {
return walk(prefix) != null;
}
private Node walk(String s) {
Node n = root;
for (char c : s.toCharArray()) {
n = n.next[c - 'a'];
if (n == null) return null;
}
return n;
}
}Verdict: Fast and simple.