class TrieNode {
TrieNode nodes[];
boolean isSentence; //称为一个句子的话仍然可能会有子节点
int count; //表示当前节点实际上代表了多少个相同的单词
public TrieNode() {
nodes = new TrieNode[26]; //26个英文字母
isSentence = false;
count = 0;
}
}
//单论小写字母
void buildTrie(String str, TrieNode root) {
if (root == null)
return;
TrieNode curr = root;
char[] arr = str.toCharArray();
for (int i = 0; i < arr.length; ++i) {
if (curr.nodes[arr[i] - 'a'] == null) {
curr.nodes[arr[i] - 'a'] = new TrieNode();
}
curr = curr.nodes[arr[i] - 'a'];
if (i == arr.length - 1) {
curr.isSentence = true;
curr.count++;
}
}
}
int findStr(String str, TrieNode root) {
if (root == null)
return 0;
TrieNode curr = root;
char arr[] = str.toCharArray();
for (int i = 0; i < arr.length; ++i) {
if (curr.nodes[arr[i] - 'a'] == null)
return 0;
curr = curr.nodes[arr[i] - 'a'];
if (arr.length - 1 == i && curr.isSentence) {
return curr.count;
}
}
return 0;
}
public static void main(String[] args) {
print p = new print();
TrieNode node = new TrieNode();
p.buildTrie("wangcheng", node);
p.buildTrie("abc", node);
p.buildTrie("abc", node);
p.buildTrie("hello", node);
p.buildTrie("hello", node);
int a = p.findStr("wangcheng", node);
System.out.println(a);
}