//建立字典树,相关资料可以在网上查到
//查找这一步需要用到递归
//注意此题容易超时,需要使用c的输入输出和c字符串
#include<stdio.h>
#include<string.h>
using namespace std;
class Node{
public:
Node* next[26];
bool flag;
Node(){
for(int i = 0; i < 26; i++) next[i] = NULL;
flag = false;
}
};
Node* root;
int n, m;
char tar[20];
char s[20];
void build(char*);
void find(Node*, char*);
int main(){
root = new Node();
scanf("%d", &n);
for(int i = 0; i < n; i++){
scanf("%s", s);
build(s);
}
scanf("%d", &m);
for(int i = 0; i < m; i++){
scanf("%s", tar);
Node* cur = root;
for(unsigned int i = 0; i < strlen(tar); i++){
int pos = tar[i] - 'a';
if(cur->next[pos] == NULL){
cur = NULL;
break;
}
cur = cur->next[pos];
}
find(cur, tar);
printf("\n");
}
return 0;
}
void build(char* str){
Node* cur = root;
for(unsigned int i = 0; i < strlen(str); i++){
int to = str[i] - 'a';
if(cur->next[to] == NULL){
cur->next[to] = new Node();
}
cur = cur->next[to];
}
cur->flag = true;
}
void find(Node* root, char* str){
if(root == NULL){
return;
}
if(root->flag){
printf("%s\n", str);
}
for(int i = 0; i < 26; i++){
char temp[20];
unsigned int len = strlen(str);
for(unsigned int j = 0; j < len; j++) temp[j] = str[j];
temp[len] = i + 'a';
temp[len + 1] = '\0';
find(root->next[i], temp);
}
}
//presented by 大吉大利,今晚AC
合肥工业大学oj 1201 字符前缀
猜你喜欢
转载自blog.csdn.net/lalala_HFUT/article/details/87943363
今日推荐
周排行