[LeetCode]208. 实现 Trie(前缀树)(JAVA实现)
1. 题目
2. 读题(需要重点注意的东西)
3. 解法
详细的构建思路,请看下文 5. 所用到的数据结构与算法思想
class Trie {
private class TrieNode {
private boolean isEnd;
private TrieNode[] next;
public TrieNode() {
isEnd = false;
next = new TrieNode[26];
}
}
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 cur = root;
for (int i = 0, len = word.length(), ch; i < len; i++) {
ch = word.charAt(i) - 'a';
if (cur.next[ch] == null)
cur.next[ch] = new TrieNode();
cur = cur.next[ch];
}
cur.isEnd = true;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
TrieNode cur = root;
for (int i = 0, len = word.length(), ch; i < len; i++) {
ch = word.charAt(i) - 'a';
if (cur.next[ch] == null)
return false;
cur = cur.next[ch];
}
return cur.isEnd;
}
/**
* Returns if there is any word in the trie that starts with the given prefix.
*/
public boolean startsWith(String prefix) {
TrieNode cur = root;
for (int i = 0, len = prefix.length(), ch; i < len; i++) {
ch = prefix.charAt(i) - 'a';
if (cur.next[ch] == null)
return false;
cur = cur.next[ch];
}
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);
*/
4. 可能有帮助的前置习题
5. 所用到的数据结构与算法思想
6. 总结
这是前缀树相关问题的基础,一般题目是不会给出前缀树的相关定义代码的,如果在解题中要利用前缀树,就必须自己在解题时定义。
如果无法实现,请看Java数据结构—Trie(字典树/前缀树)一篇弄懂前缀树!图解、完整注释!,并将代码熟记直至能够完整默写。