public class Trie {
public static class TrieNode {
private final int N = 26;
private TrieNode[] links;
private boolean isEnd = false;
public TrieNode() {
links = new TrieNode[N];
}
public boolean containsKey(char ch) {
return links[ch-'a'] != null;
}
public void insertKey(char ch, TrieNode node) {
links[ch-'a'] = node;
}
public TrieNode getNode(char ch) {
return links[ch-'a'];
}
public void setEnd() {
isEnd = true;
}
public boolean getEnd() {
return isEnd;
}
}
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 node = root;
for (int i=0; i<word.length(); i++) {
char curr = word.charAt(i);
if (!node.containsKey(curr)) {
node.insertKey(curr, new TrieNode());
}
node = node.getNode(curr);
}
node.setEnd();
}
/** Returns null or a TrieNode which the last char in the word points **/
public TrieNode searchPrefix(String word) {
TrieNode node = root;
for (int i=0; i<word.length(); i++) {
char curr = word.charAt(i);
if (!node.containsKey(curr)) {
node = null;
break;
}
node = node.getNode(curr);
}
return node;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
TrieNode node = searchPrefix(word);
return node!=null && node.getEnd();
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
TrieNode node = searchPrefix(prefix);
return node != null;
}
}
Leetcode 208. Implement Trie (Prefix Tree)
最新推荐文章于 2022-03-04 22:30:33 发布