题目链接
大意是判断所给字符串组中是否存在与查询串仅一字符之差的字符串。
关于字符串查询的题,可以用字典树(Trie树)来解,第一次接触,做个小记。在查询时按题目要求进行查询。
代码:
#define _CRT_SECURE_NO_DEPRECATE
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<vector>
#include<queue>
#include<map>
#include<cmath>
#include<algorithm>
#include<climits>
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
typedef map<string, int> M;
typedef vector<int> V;
typedef queue<int> Q;
const int maxn = 6 * 100000 + 10;
const int N = 3;
struct trie
{
trie* next[N];
int count;
};
typedef trie* link;
link create()
{
link p = new trie;
p->count = 0;
for (int i = 0; i < N; ++i)
p->next[i] = NULL;
return p;
}
void insert(char* s, link root)
{
char* p = s;
link node = root;
while (*p)
{
if (node->next[*p - 'a']==NULL)
node->next[*p - 'a'] = create();
node = node->next[*p - 'a'];
++p;
}
node->count++;
return;
}
bool query(char* s, link pos,int cnt)
{
if (*s == '\0')
{
if (cnt == 1 && pos->count)
return true;
else
return false;
}
for (int i = 0; i < N; ++i)
{
if (i != *s - 'a' && cnt==0 && pos->next[i])
{
if (query(s + 1, pos->next[i], 1))
return true;
}
if (i == *s - 'a' && pos->next[i])
{
if (query(s + 1, pos->next[i], cnt))
return true;
}
}
return false;
}
char s[maxn];
int main()
{
int n,m,k,i,j;
link root=create();
cin >> n >> m;
for (i = 0; i < n; ++i)
{
scanf("%s", s);
insert(s, root);
}
for (i = 0; i < m; ++i)
{
scanf("%s", s);
if (query(s, root, 0))
cout << "YES\n";
else
cout << "NO\n";
}
return 0;
}