TrieNode Class
First lets look at TrieNode
class:
class TrieNode {
private boolean isLeaf;
private TrieNode[] children = new TrieNode[26];
}
Sometimes people also use names like isWord
, isEnd
for isLeaf
.
Trie Class
Trie class methods are same as Map-based Trie Implementation#Trie Class.
Code
Java
class Trie {
static class TrieNode {
private boolean isLeaf;
private TrieNode[] children = new TrieNode[26];
}
public TrieNode root;
/** Initialize your data structure here. */
public Trie() {
this.root = new TrieNode();
}
/** Inserts a word into the trie. */
public void insert(String word) {
TrieNode curr = this.root;
for (char c: word.toCharArray()) {
int idx = c - 'a';
if (curr.children[idx] == null) {
curr.children[idx] = new TrieNode();
}
curr = curr.children[idx];
}
curr.isLeaf = true;
}
/** Returns true if the word is in the trie. */
public boolean exists(String word) {
TrieNode curr = root;
for (char c: word.toCharArray()) {
int idx = c - 'a';
curr = curr.children[idx];
if (curr == null) {
return false;
}
}
return curr.isLeaf;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
TrieNode curr = root;
for (char c: prefix.toCharArray()) {
int idx = c - 'a';
curr = curr.children[idx];
if (curr == null) {
return false;
}
}
return true;
}
}