Trie树
学习自三叶姐208. 实现 Trie (前缀树) - 力扣(LeetCode)
使用二维数组进行模拟
class Trie {
int N = 100010;
int[][] trie;
int[] cnt;
int idx;
public Trie() {
trie = new int[N][26];
cnt = new int[N];
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(trie[p][u] == 0) trie[p][u] = ++idx;
p = trie[p][u];
}
cnt[p] ++;
}
// 查找字符串
public boolean search(String word) {
int p = 0;
for(int i = 0;i<word.length;i++){
int u = word.charAt(i) - 'a';
if(trie[p][u] == 0) return false;
p = trie[p][u];
}
return cnt[p] != 0;
}
// 判断是否具有prefix前缀
public boolean startsWith(String prefix) {
int p = 0;
for(int i = 0;i<word.length;i++){
int u = word.charAt(i) - 'a';
if(trie[p][u] == 0) return false;
p = trie[p][u];
}
return true;
}
}
使用结构体进行模拟
class Trie {
class TrieNode {
boolean end;
TrieNode[] son = new TrieNode[26];
}
TrieNode root;
public Trie() {
root = new TrieNode();
}
public void insert(String word) {
TrieNode p = root;
for(int i = 0;i<word.length();i++){
int u = word.charAt(i) - 'a';
if(p.son[u] == null) p.son[u] = new TrieNode();
p = p.son[u];
}
p.end = true;
}
public boolean search(String word) {
TrieNode p = root;
for(int i = 0;i<word.length();i++){
int u = word.charAt(i) - 'a';
if(p.son[u] == null) return false;
p = p.son[u];
}
// p.end = true;
return p.end;
}
public boolean startsWith(String prefix) {
TrieNode p = root;
for(int i = 0;i<prefix.length();i++){
int u = prefix.charAt(i) - 'a';
if(p.son[u] == null) return false;
p = p.son[u];
}
return true;
}
}