LeetCode.208 前缀树
class Trie {
private final int MAX_LEN = 26;
private boolean isEnd = false;
private Trie[] next = new Trie[MAX_LEN]; // 定义一个以Trie为对象的数组
/** Initialize your data structure here. */
public Trie() {
}
/** Inserts a word into the trie. */
public void insert(String word) {
Trie root = this; // 获取前最缀树的根节点
for (int i = 0; i < word.length(); i++) {
if (root.next[word.charAt(i) - 'a'] == null) { // 当前字符对应的前缀树的节点为空
root.next[word.charAt(i) - 'a'] = new Trie(); // 新建一个对象插入到前缀树的节点中
}
root = root.next[word.charAt(i) - 'a'];
}
root.isEnd = true; // 当字符全部插入到前缀树中,标记最后一个字符在前缀树中的flag为True。此外,其余字符在前缀树中的flag为False。
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
Trie root = this;
for (int i = 0; i < word.length(); i++) {
if (root.next[word.charAt(i) - 'a'] == null) {
return false;
}
root = root.next[word.charAt(i) - 'a'];
}
return root.isEnd;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
Trie root = this;
for (int i = 0; i < prefix.length(); i++) {
if (root.next[prefix.charAt(i) - 'a'] == null) {
return false;
}
root = root.next[prefix.charAt(i) - 'a'];
}
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);
*/
将单词插入前缀树示例: