链表对象的方式实现
class Trie {
class Node{
boolean end;
// 26个字母
Node[] tns = new Node[26];
}
Node root;
public Trie() {
root = new Node();
}
public void insert(String word) {
Node p = root;
for (int i = 0; i < word.length(); i++){
int u = word.charAt(i) - 'a';
if (p.tns[u] == null){
p.tns[u] = new Node();
}
p = p.tns[u];
}
p.end = true;
}
public boolean search(String word) {
Node p = root;
for (int i = 0; i < word.length(); i++){
int u = word.charAt(i) - 'a';
if (p.tns[u] == null){
return false;
}
p = p.tns[u];
}
return p.end;
}
public boolean startsWith(String prefix) {
Node p = root;
for (int i = 0; i < prefix.length(); i++){
int u = prefix.charAt(i) - 'a';
if (p.tns[u] == null){
return false;
}
p = p.tns[u];
}
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);
*/
数组的方式实现
class Trie {
int n ;
int m;
boolean[] end;
int[][] tr;
int idx;
public Trie() {
n = 100009;
m = 26;
end = new boolean[n];
tr = new int[n][m];
idx = 0;
}
public void insert(String word) {
int p = 0;
for (int i = 0; i < word.length(); i++){
int u = word.charAt(i) - 'a';
if (tr[p][u] == 0){
tr[p][u] = ++idx;
}
p = tr[p][u];
}
end[p] = true;
}
public boolean search(String word) {
int p = 0;
for (int i = 0; i < word.length(); i++){
int u = word.charAt(i) - 'a';
if (tr[p][u] == 0){
return false;
}
p = tr[p][u];
}
return end[p];
}
public boolean startsWith(String prefix) {
int p = 0;
for (int i = 0; i < prefix.length(); i++){
int u = prefix.charAt(i) - 'a';
if (tr[p][u] == 0){
return false;
}
p = tr[p][u];
}
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);
*/