本题使用 map 数据结构,暴力搜索即可。首先存储数字信息全文,将关键字序号和关键字信息存入结构体,将关键字信息的前4个数字和对应的关键字序号存入 map;然后从前到后搜索数字信息全文,如果全文中连续 4 个数字和某个关键字信息的前 4 个数字相同,则比较两者的后续字符,如果全部相同,则匹配成功,输出关键字序号;否则从全文原位置继续向后搜索,直到搜索完全文。
#include <iostream>
#include <string>
#include <map>
using namespace std;
const int MAXN = 10005;
struct keyword //关键字
{
int num; //序号
string message; //信息
}key[MAXN];
int main()
{
int M, N; //数字信息行数,关键字个数
string full; //数字信息全文
string temp; //每次读一行
map<string, int> mp; //关键字信息的前4个数字-关键字序号
while (cin >> M >> N)
{
full = ""; //清空上个测试用例的全文
mp.erase(mp.begin(), mp.end()); //清空map
for (int i = 0; i < M; i++) //读入全文
{
cin >> temp;
full += temp;
}
//读入关键字序号和信息,并将关键字信息的前4个数字和关键字序号存入map
for (int i = 1; i <= N; i++)
{
cin >> temp >> temp >> temp >> key[i].message; //前三个temp读取[Key No. i]
key[i].num = i;
mp[key[i].message.substr(0, 4)] = key[i].num;
}
int total = 0; //查找到的关键字的数量
int len = full.size(); //全文字符数
for (int i = 0; i <= len - 4; i++) //从前到后依次查找
{
//全文中从第i个位置开始的4个字符在map中是否存在
if (mp.find(full.substr(i, 4)) != mp.end())
{
string nowKey = key[mp[full.substr(i, 4)]].message; //关键字信息
int nowLen = nowKey.size(); //关键字信息长度
bool flag = true; //关键字和全文后续字符是否匹配
int j, k;
//对关键字和全文的后续字符依次匹配
for (j = i + 4, k = 4; j < len && k < nowLen; j++, k++)
{
if (full[j] != nowKey[k]) //对应字符不同,匹配失败
flag = false;
}
if (flag == true && k == nowLen) //匹配成功
{
++total;
if (total == 1)
cout << "Found key:";
cout << " [Key No. " << key[mp[full.substr(i, 4)]].num << "]";
mp.erase(full.substr(i, 4)); //清楚该关键字,避免重复输出
}
}
}
if (total == 0) //没有查找到任何关键字
cout << "No key can be found!";
cout << endl;
}
return 0;
}
继续加油。