package Trie;
/**
* 字典树
* */
public class DicTree {
public static Node root;
static class Node {
char c;
int num;
Node[] son;
public Node() {
this.son = new Node[26];
}
}
public DicTree() {
this.root = new Node();
}
public static void insert(String str) {
if (str == null || str.length() == 0)
return;
char[] chars = str.toCharArray();
int pos;
Node now = root;
for (int i = 0, length = chars.length; i < length; i++) {
Node newNode = new Node();
pos = chars[i] - 'a';
if (now.son[pos] == null) {
now.son[pos].num++;
} else {
now.son[pos].num = 1;
}
now = now.son[pos];
}
}
//求某字符串的数量
public static int count(String str) {
char[] chars = str.toCharArray();
Node now = root;
for (int i = 0; i < str.length(); i++) {
int pos = chars[i] - 'a';
now = now.son[pos];
}
return now.num;
}
}
相关文章: