version at: 2022-04-24
class Trie {
private final static int N = 26;
Trie[] childs;
boolean isEnd;
public Trie() {
this.childs = new Trie[N];
this.isEnd = false;
}
public void insert(String word) {
Trie root = this;
for (int i = 0; i < word.length(); i++) {
int index = word.charAt(i) - 'a';
if (root.childs[index] == null) root.childs[index] = new Trie();
root = root.childs[index];
}
root.isEnd = true;
}
public boolean search(String word) {
Trie node = findPrefixNode(word);
return node != null && node.isEnd;
}
public boolean startsWith(String prefix) {
return null != findPrefixNode(prefix);
}
public Trie findPrefixNode(String word) {
Trie root = this;
for (int i = 0; i < word.length(); i++) {
int index = word.charAt(i) - 'a';
if (root.childs[index] == null) return null;
root = root.childs[index];
}
return root;
}
}
/**
* Your Trie object will be instantiated and called as such:
* Trie obj = new Trie();
* obj.insert(word);
* boolean param_2 = obj.search(word);
* boolean param_3 = obj.startsWith(prefix);
*/
class Trie {
static int childNumber = 26;
boolean isWord;
Trie[] next;
/** Initialize your data structure here. */
public Trie() {
next = new Trie[childNumber];
isWord = false;
}
/** Inserts a word into the trie. */
public void insert(String word) {
var p = this;
for (int i = 0; i < word.length(); i++){
int index = word.charAt(i) - 'a';
if (p.next[index] == null) p.next[index] = new Trie();
p = p.next[index];
}
p.isWord = true;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
var p = this;
for (int i = 0; i < word.length(); i++){
int index = word.charAt(i) - 'a';
if (p.next[index] == null) return false;
p = p.next[index];
}
return p.isWord == true;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
var p = this;
for (int i = 0; i < prefix.length(); i++){
int index = prefix.charAt(i) - 'a';
if (p.next[index] == null) return false;
p = p.next[index];
}
return true;
}
}
/**
* Your Trie object will be instantiated and called as such:
* Trie obj = new Trie();
* obj.insert(word);
* boolean param_2 = obj.search(word);
* boolean param_3 = obj.startsWith(prefix);
*/