知识点:字符串哈希,KMP算法
难度:3
这个题算是入门KMP之后最简单的非模板题,题目里面没有说要输出所有满足条件的子串,那么我就输出了一个,也就是最长的,第一个找到的子串,就过了,但是对这种题的时间复杂度还是不很熟练,写之前不确定这种字符串哈希+KMP的写法时间够不够,写完才发现过了,
#include <bits/stdc++.h>
using namespace std;
typedef unsigned long long ull;
const int N = 1e6 + 5;
const int P = 131;
int ne[N];
ull h[N], p[N];
string s;
void init(int len) {
h[0] = 0;
p[0] = 1;
for (int i = 1; i <= len; i++) {
h[i] = h[i - 1] * P + s[i];
p[i] = p[i - 1] * P;
}
}
ull get(int l, int r) {
return h[r] - h[l - 1] * p[r - l + 1];
}
int main() {
cin >> s;
s = " " + s;
int len = (int) s.size() - 1;
init(len);
ne[1] = 0;
for (int i = 2, j = 0; i <= len; i++) {
while (j && s[i] != s[j + 1]) j = ne[j];
if (s[i] == s[j + 1]) j++;
ne[i] = j;
}
int ind = len;
int ok = 0;
while (ne[ind]) {
int t = ne[ind];
for (int i = 2; i <= len - 1 - t + 1; i++) {
if (get(i, i + t - 1) == get(1, t)) {
ok = 1;
cout << s.substr(i, t);
break;
}
}
if (ok) break;
ind = ne[ind];
}
if (!ok) cout << "Just a legend";
return 0;
}