leetcode 链接:https://leetcode-cn.com/problems/implement-trie-prefix-tree/
题目
解法
题目限定了字母为小写字母 a-z,所以可以创建一个大小为 26 的数组,每个数组位置代表一个字母
public class Trie {
// 根节点
private final Node root;
private class Node {
private static final int size = 26;
// 当前节点是否为某个单词的末位
boolean isWord;
// 指向子节点
Node[] next;
public Node(boolean isWord) {
this.isWord = isWord;
next = new Node[size];
}
public Node() {
this(false);
}
public boolean containsKey(char ch) {
return next[ch - 'a'] != null;
}
public Node get(char ch) {
return next[ch - 'a'];
}
public void put(char ch, Node node) {
next[ch - 'a'] = node;
}
}
public Trie() {
this.root = new Node();
}
/**
* Inserts a word into the trie.
*/
public void insert(String word) {
Node curr = root;
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
if (!curr.containsKey(ch)) {
curr.put(ch, new Node());
}
curr = curr.get(ch);
}
curr.isWord = true;
}
/**
* Returns if the word is in the trie.
*/
public boolean search(String word) {
Node curr = root;
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
if (!curr.containsKey(ch)) {
return false;
}
curr = curr.get(ch);
}
return curr.isWord;
}
/**
* Returns if there is any word in the trie that starts with the given prefix.
*/
public boolean startsWith(String prefix) {
Node curr = root;
for (int i = 0; i < prefix.length(); i++) {
char ch = prefix.charAt(i);
if (!curr.containsKey(ch)) {
return false;
}
curr = curr.get(ch);
}
return true;
}
}