前缀树的介绍与源码
前缀数是经常用到的一种数据结构。
主要思路是用边来记录数据,用点来记录有多少字符串经过某条边以及把某条边作为结尾。
主要用于查找一个结构中有多少以某个字符开头的结果,或者某一个字符出现了几次。下面直接上代码。
package Main;
/**
* @author Leslie
*
*/
public class Main {
public static class TrieNode {
public int path;
public int end;
public TrieNode[] nexts;
public TrieNode() {
path = 0;
end = 0;
nexts = new TrieNode[26];
}
}
public static class Trie {
private TrieNode root;
public Trie() {
root = new TrieNode();
}
public void insert(String word) {
if (word == null) {
return;
}
TrieNode node = root;
char[] chs = word.toCharArray();
int index = 0;
for (int i = 0; i < chs.length; i++) {
index = chs[i] - 'a';
if (node.nexts[index] == null) {
node.nexts[index] = new TrieNode();
}
node = node.nexts[index];
node.path++;
}
node.end++;
}
public int search(String word) {
if (word == null) {
return 0;
}
char[] chs = word.toCharArray();
TrieNode node = root;
int index = 0;
for (int i = 0; i < chs.length; i++) {
index = chs[i] - 'a';
if (node.nexts[index] == null) {
return 0;
}
node = node.nexts[index];
}
return node.end;
}
public void delete(String word) {
if (word == null) {
return;
}
if (search(word) == 0) {
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.nexts[index].path == 0) {
node.nexts[index] = null;
return;
}
node = node.nexts[index];
}
node.end--;
}
public int prefixNumber(String preStr) {
if (preStr == null) {
return 0;
}
char[] chs = preStr.toCharArray();
TrieNode node = root;
int index = 0;
for (int i = 0; i < chs.length; i++) {
index = chs[i] - 'a';
if (node.nexts[index] == null) {
return 0;
}
node = node.nexts[index];
}
return node.path;
}
}
public static void main(String[] args) {
Trie Test = new Trie();
Test.insert("zjz");
System.out.println(Test.search("zjz"));
System.out.println(Test.prefixNumber("z"));
Test.delete("zjz");
System.out.println(Test.search("zjz"));
System.out.println(Test.prefixNumber("z"));
}
}