建立字典,查找单词。很容易想到字典树。
字典树是用空间换时间。所以空间消耗极大。
另外这个题目有一些不同之处:
1.要计算的是所求单词在字典中的字符串中出现的次数,不一定要从第一个字母出现,字符串中包含所求单词也可以
2.同一个字符串中出现两个相同的字串,只算出现一次
(可见实例中的“d”)
AC代码:
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
#define NULL 0
const int num_chars = 26;
struct trieNode
{
char* data;
trieNode* branch[num_chars];
int num; //在字典中,记录该字符串已经出现的次数,即题目所求
int mark; //用于标记同一个单词中的重复字符串
trieNode(){
data = NULL;
num = 0;
mark = 0;
for (int i = 0; i < num_chars; i++){
branch[i] = NULL;
}
}
};
trieNode* root;
int insert(char* word){
int result = 1, position = 0;
if (root == NULL) //如果是第一次插入,先建树
root = new trieNode;
int char_code;
trieNode* location = root;
while (*word != '\0'){ //当单词全部输入遍历完之后,退出循环
char_code = *word - 'a';
if (location->branch[char_code] == NULL) //如果该字串是第一次在字典中出现,则先new
location->branch[char_code] = new trieNode;
location = location->branch[char_code];
position++;
word++;
if (location->mark == 0){ //如果这个字串是第一次在该字符串中出现,则记录加一,并且标记,如果同一个字符串再出现同样的字串,则不加1
location->num++;
location->mark = 1;
};
}
/*if (location->data != NULL){
if (location->mark == 0){
location->num++;
location->mark = 1;
}
return 0;
}
else{
if (location->mark == 0){
location->num++;
location->mark = 1;
}
}*/
return result;
}
int search(char* word){
int position = 0;
int char_code;
trieNode *location = root;
while (location != NULL && *word != '\0'){
char_code = *word - 'a';
location = location->branch[char_code];
position++;
word++;
}
if (location == NULL){
return 0;
}
return location->num;
}
void frash(char* word){ //刷新标记,便于判断下一个字符串
int position = 0;
int char_code;
trieNode *location = root;
while (location != NULL && *word != '\0'){
char_code = *word - 'a';
location = location->branch[char_code];
location->mark = 0;
position++;
word++;
}
if (location != NULL){
location->mark = 0;
}
}
int main(){
// freopen("TestDate.txt", "r", stdin);
int n, m;
cin >> n;
char d[21];
while (n--){
cin >> d;
char* ds = d;
while (*ds != '\0'){ //由于是包含关系,所以要将字符串的每一个字母做开头都加入树中
insert(ds);
ds++;
}
ds = d;
while (*ds != '\0'){
frash(ds);
ds++;
}
}
cin >> m;
while (m--){
cin >> d;
cout << search(d) << endl;
}
return 0;
}