J 最大值
题目地址:
基本思路:
我们观察题目的意思,然后我们联想一下KMP中的next数组的定义,next数组是在当前位置前后缀相等的长度,其实和题目中要找的AC串是一个意思,因此在next数组中找最大就行了。
参考代码:
#pragma GCC optimize(2)
#pragma GCC optimize(3)
#include <bits/stdc++.h>
using namespace std;
#define IO std::ios::sync_with_stdio(false)
#define int long long
#define rep(i, l, r) for (int i = l; i <= r; i++)
#define per(i, l, r) for (int i = l; i >= r; i--)
#define mset(s, _) memset(s, _, sizeof(s))
#define pb push_back
#define pii pair <int, int>
#define mp(a, b) make_pair(a, b)
#define INF (int)1e18
inline int read() {
int x = 0, neg = 1; char op = getchar();
while (!isdigit(op)) { if (op == '-') neg = -1; op = getchar(); }
while (isdigit(op)) { x = 10 * x + op - '0'; op = getchar(); }
return neg * x;
}
inline void print(int x) {
if (x < 0) { putchar('-'); x = -x; }
if (x >= 10) print(x / 10);
putchar(x % 10 + '0');
}
namespace KMP{
vector<int> next;
void build(const string &pattern){
int n = pattern.length();
next.resize(n + 1);
for (int i = 0, j = next[0] = -1; i < n; next[++i] = ++j){
while(~j && pattern[j] != pattern[i]) j = next[j];
}
}
vector<int> match(const string &pattern, const string &text){
vector<int> res;
int n = pattern.length(), m = text.length();
build(pattern);
for (int i = 0, j = 0; i < m; ++i){
while(j > 0 && text[i] != pattern[j]) j = next[j];
if (text[i] == pattern[j]) ++j;
if (j == n) res.push_back(i - n + 1), j = next[j];
}
return res;
}
};
string str;
signed main() {
IO;
int t;
cin >> t;
while (t--){
cin >> str;
KMP::build(str);
int ans = -1;
for(auto it : KMP::next){
ans = max(ans,it);
}
cout << ans << '\n';
}
return 0;
}
京公网安备 11010502036488号