1015 dictionary tree, 1015 dictionary
Dictionary tree: as its name implies, it is used for searching by characters. However, it only counts the number of words prefixed with a character or string. If the dictionary does not have this prefix, 0 is returned. If yes, the number is returned.
Create tree: traverse the number of string parts in sequence based on the given string. If so, run num ++ to view the next character. No. Create a new node, n ++, and view the next node.
Until the string is traversed.
View: the general operation is the same as the creation operation. After the string is traversed, num is returned, and 0 is returned if num is returned;
This is only an English dictionary query. If it is all the characters in the world, an error will occur. You can change the child array in the node to a dynamic array, and then, like the English dictionary, but I haven't done it yet ,,,,,,,,,,
Source code:
# Include <iostream>
# Include <string. h>
# Include <stdio. h>
Using namespace std;
// Create a dictionary Tree node
Typedef struct Trie {
Int num; // number of records
Struct Trie * child [26]; // 26 letter branches
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'; // identify the character
If (p-> child [temp] = NULL) {// determines whether the object exists.
P-> child [temp] = new Trie;
}
P = p-> child [temp]; // The root node does not need a total number, which indicates the number of words contained in the entire dictionary. Therefore, 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 ++) {// traverse the given string
Int temp = str [I]-'A ';
If (p-> child [temp] = NULL) {// determines whether the existence 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; // The maximum number of words in the dictionary
While (n --){
Cin> str;
Create (str, trie );
}
Cin> m; // Number of words to be searched
While (m --){
Cin> str;
Cout <check (str, trie) <endl;
}
}
Note: you are not familiar with some functions of c ++. str. length (); originally written as 'str. length'; length is a function, not an attribute.