Trie
Trie (Prefix Tree)
1. Introduction
2. Implementation
public class Trie {
class TrieNode {
char val;
TrieNode[] childNode;
boolean isWord;
public TrieNode() {
childNode = new TrieNode[26];
}
}
TrieNode root;
/** Initialize your data structure here. */
public Trie() {
root = new TrieNode();
}
/** Inserts a word into the trie. */
public void insert(String word) {
if (word == null || word.length() == 0) {
return;
}
TrieNode node = root;
for (char c : word.toCharArray()) {
int index = c - 'a';
if (node.childNode[index] == null) {
node.childNode[index] = new TrieNode();
node.childNode[index].val = c;
}
node = node.childNode[index];
}
node.isWord = true;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
if (word == null || word.length() == 0) {
return false;
}
TrieNode node = root;
for (char c : word.toCharArray()) {
int index = c - 'a';
if (node.childNode[index] == null) {
return false;
}
else {
node = node.childNode[index];
}
}
return node.isWord;
}
/** 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 false;
}
TrieNode node = root;
for (char c : prefix.toCharArray()) {
int index = c - 'a';
if (node.childNode[index] == null) {
return false;
}
else {
node = node.childNode[index];
}
}
return true;
}
}3. Time & Space Complexity
4. Thoughts
5. Interview Questions
Last updated