class TrieTree {
TrieNode root;
public TrieTree() {
root = new TrieNode();
}
public void insert(String word) {
TrieNode node = root;
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
if (!node.containsKey(ch)) {
node.put(ch, new TrieNode());
}
node = node.get(ch);
}
node.setEnd();
}
public boolean search(String word) {
TrieNode node = searchPrefix(word);
return node != null && node.isEnd();
}
public boolean startsWith(String prefix) {
TrieNode node = searchPrefix(prefix);
return node != null;
}
private TrieNode searchPrefix(String word) {
TrieNode node = root;
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
if (node.containsKey(ch)) {
node = node.get(ch);
} else {
return null;
}
}
return node;
}
}
public class TrieNode {
TrieNode[] nodes;
boolean isEnd = false;
public TrieNode() {
nodes = new TrieNode[26];
}
public boolean containsKey(char ch) {
return nodes[ch - 'a'] != null;
}
public TrieNode get(char ch) {
return nodes[ch - 'a'];
}
public void put(char ch, TrieNode node) {
nodes[ch - 'a'] = node;
}
public void setEnd() {
isEnd = true;
}
public boolean isEnd() {
return this.isEnd;
}
}
05-23
215
09-30
299
01-08
277
01-21
522
10-03
464
03-25