TrieNode 实现
class TrieNode {
private TrieNode[] links;
private final int R = 26;
private boolean isEnd;
private String word;
public TrieNode() {
links = new TrieNode[R];
}
public boolean containsKey(char ch) {
return links[ch - 'a'] != null;
}
public TrieNode get(char ch) {
return links[ch - 'a'];
}
public void set(char ch, TrieNode node) {
links[ch - 'a'] = node;
}
public void setEnd() {
isEnd = true;
}
public boolean isEnd() {
return isEnd;
}
public void setWord(String word) {
this.word = word;
}
public String getWord() {
return word;
}
}
Trie实现
class Trie {
private TrieNode root;
public Trie() {
root = new TrieNode();
}
public void insert(String word) {
TrieNode node = root;
for (char ch : word.toCharArray()) {
if (!node.containsKey(ch)) node.put(ch, new TrieNode());
node = node.get(ch);
}
node.setEnd();
node.setWord(word);
}
public TrieNode searchPrefix(String word) {
TrieNode node = root;
for (char ch : word.toCharArray()) {
if (!node.containsKey(ch)) return null;
node = node.get(ch);
}
return node;
}
public boolean search(String word) {
TrieNode node = searchPrefix(word);
return node != null && node.isEnd();
}
}