18. Trie
search prefix
208. Implement Trie
TrieNode class
Trie class
insert, search, startsWith function
class TrieNode{
public TrieNode[] children;
public boolean isWord;
public TrieNode(){
children = new TrieNode[26];
isWord = false;
}
}
class Trie {
private TrieNode root;
/** Initialize your data structure here. */
public Trie() {
root = new TrieNode();
}
/** Inserts a word into the trie. */
public void insert(String word) {
TrieNode p = root;
for(int i=0; i<word.length(); i++){
int c = word.charAt(i)-'a';
if(p.children[c] == null){
p.children[c] = new TrieNode();
}
p = p.children[c];
}
p.isWord = true;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
TrieNode p = root;
for(int i=0; i<word.length(); i++){
int c = word.charAt(i)-'a';
if(p.children[c] == null){
return false;
}
p = p.children[c];
}
return p.isWord;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
TrieNode p = root;
for(int i=0; i<prefix.length(); i++){
int c = prefix.charAt(i)-'a';
if(p.children[c] == null){
return false;
}
p = p.children[c];
}
return true;
}
}
Last updated
Was this helpful?