字典树是一种树形结构,优点是利用字符串的公共前缀来节约存储空间,比如加入“inn int tea ton"之后的字典树,如下:
字典树的基本性质如下:
根节点没有字符路径。除根节点外,每一个节点都被一个字符路径找到。
从根节点到某一节点,将路径上经过的字符连接起来,为扫过的对应字符串。
每个节点向下所有的字符路径上的字符都不同。
问题如下:
实现字典树结构,包含以下四个主要功能:
void insert(String word):添加word,可重复添加
void delete(String word):删除word,如果word添加过多次,仅删除一个
boolean search(String word):查询word是否在字典树中
int prefinNumber(String pre):返回以字符串pre为前缀的单词数量
public class Main {
public class TrieNode{
public int path; //表示有多少个单词公用这个节点
public int end;//end表示有多少个单词以这个节点结尾
public TrieNode[] map;
public TrieNode() {
path = 0;
end = 0;
map = new TrieNode[26];
}
}
public static void main(String[] args) {
}
private TrieNode root;
public void insert(String word) {
if(word == null) {
return;
}
char [] chs = word.toCharArray();
TrieNode node = root;
int index = 0;
for(int i = 0;i<chs.length;i++) {
index = chs[i] - 'a';
if(node.map[index] == null) {
node.map[index] = new TrieNode();
}
node = node.map[index];
node.path++;
}
node.end ++;
}
public void delete(String word) {
if(search(word)) {
char[] chs = word.toCharArray();
TrieNode node = root;
int index = 0;
for(int i =0;i<chs.length;i++) {
index = chs[i]- 'a';
if(node.map[index].path-- ==1) {
node.map[index] = null;
return ;
}
node = node.map[index];
}
node.end --;
}
}
private boolean search(String word) {
if(word == null) {
return false;
}
char[] chs = word.toCharArray();
TrieNode node = root;
int index = 0;
for(int i = 0;i<chs.length;i++) {
index = chs[i] -'a';
if(node.map[index] == null) {
return false;
}
node = node.map[index];
}
return node.end!=0;
}
public int prefixNumber(String pre) {
if(pre == null) {
return 0;
}
char [] chs = pre.toCharArray();
TrieNode node = root;
int index = 0;
for(int i = 0;i<chs.length;i++) {
index = chs[i] -'a';
if(node.map[index] == null) {
return 0;
}
node = node.map[index];
}
return node.path;
}
}