Dictionary tree: As the name implies, is through the character to find, but only to count the number of words prefixed with a character or string, the dictionary does not have the prefix, return 0, there is the number of returns.
Create tree: According to the given string, loop through the number of strings, if present, num++, view the next character. Does not exist, create a new node, n++, and view the next node.
Until the string is traversed.
View: As a general operation and creation, after traversing the string, there is a return of NUM, there is no return 0;
This is only an English dictionary query, if it is all the characters in the world, it will be an error, you can change the child array within the node into a dynamic array, and then, and the English dictionary, but I have not yet, the study 、、、、、、、、、、
Source:
#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace Std;
Create a dictionary tree node
typedef struct trie{
int num;//Record Count
struct Trie *CHILD[26];//26 branch of letters
Trie () {
for (int i=0;i<26;i++) {//initialization
Child[i]=null;
}
}
}trie;
Create a dictionary tree
void Create (String Str,trie *trie) {
Trie *p=trie;
for (int i=0;i< (Str.length ()); i++) {
int temp=str[i]-' a ';//judging by that character
if (p->child[temp]==null) {//To determine existence
P->child[temp]=new Trie;
}
p=p->child[temp];//root node does not need the total number, that represents the whole dictionary contains the number of words, it is directly connected to the character branch;
P->num + +;
}
}
Search by prefix
int check (string Str,trie *trie) {
Trie *p=trie;
for (int i=0;i< (Str.length ()); i++) {//traversal of the given string
int temp=str[i]-' a ';
if (p->child[temp]==null) {//judgment exists, no: 0; Yes: Next character;
return 0;
}
p=p->child[temp];
}
Return p->num;
}
int main (void) {
Trie *trie=new Trie;
int n,m;
String str;
cin>>n;//dictionary contains a maximum number of words
while (n--) {
cin>>str;
Create (Str,trie);
}
cin>>m;//finding the number of words
while (m--) {
cin>>str;
Cout<<check (Str,trie) <<endl;
}
}
Note: The use of some functions of C + + is unfamiliar, str.length (); originally written as ' str.length '; length is a function, not a property.
1015 Dictionary Tree