题目描述
已知字符串 S1S1 由某个字符串 S2S2 不断自我连接形成,但是字符串 S2S2 未知。
现给出 S1S1 的一个长度为 nn 的片段 SS,问可能的 S2S2 的最短长度是多少。
例如给出 S1S1 的一个长度为 88 的片段 PP = “cabcabcacabcabca”,求最短的 S2S2 长度,答案是 33,S2S2 可能是 “abcabc”、“cabcab”、“bcabca”等。
输入描述
第一行一个整数 nn,表示给出字符串的长度。
第二行给出字符串 S1S1 的一个子串 SS,全由小写字母组成。
输出描述
输出仅一行,包含一个整数
#include <bits/stdc++.h>
using namespace std;
int nextArry[10000];
// 定义获取next数组的函数
void getNextArry(string s) {
if (s.size() == 1) {
nextArry[0] = -1;
return;
}
nextArry[0] = -1;
nextArry[1] = 0;
int i = 2;
int cn = 0;
while (i < s.size()) {
if (s[i - 1] == s[cn]) {
nextArry[i++] = ++cn;
} else if (cn > 0) {
cn = nextArry[cn];
} else {
nextArry[i++] = 0;
}
}
}
int main() {
int n, result = 0;
cin >> n;
char arry[n];
for (int i = 0; i < n; i++) {
cin >> arry[i];
}
string s = arry;
getNextArry(s);
for (int i = 0; i < n - 1; i++) {
result = max(result, nextArry[i]);
// cout << nextArry[i] << endl;
}
cout << result;
return 0;
}