#include <bits/stdc++.h>
using namespace std;
char s[1048577];
int n, m, tag[210];
int max_size, ch[210][30];
void add_str () {
int l = strlen (s), now = 0;
for (int i = 0; i < l; ++i) {
if (!ch[now][s[i] - 'a']) {
ch[now][s[i] - 'a'] = ++max_size;
}
now = ch[now][s[i] - 'a'];
}
tag[now] = true; //结束标志
}
int match[1048577];
int get_ans () {
int l = strlen (s), now = 0;
memset (match, 0, sizeof (match));
match[0] = true;
for (int i = 0; i < l; ++i) {
if (match[i]) {
//match[i]代表前i位的前缀可用
//从i + 1位 (字符串第i位) 回溯原点去找
int pos = 0, t = i;
while (ch[pos][s[t] - 'a'] && t < l) {
pos = ch[pos][s[t] - 'a'];
if (tag[pos] == true) {
//结束标记
match[t + 1] = true;
}
++t;
}
}
}
for (int i = l; i >= 0; --i) {
if (match[i]) return i;
}
}
int main () {
cin >> n >> m;
for (int i = 1; i <= n; ++i) {
scanf ("%s", s);
add_str ();
}
for (int i = 1; i <= m; ++i) {
scanf ("%s", s);
cout << get_ans () << endl;
}
}
原文:https://www.cnblogs.com/maomao9173/p/10441536.html