第一个题解
2025-11-06 20:03:57
发布于:浙江
2阅读
0回复
0点赞
#include <iostream>
#include <vector>
#include <string>
using namespace std;
// 计算前缀函数
vector<int> compute_prefix(const string& s) {
int n = s.size();
vector<int> pi(n, 0);
for (int i = 1; i < n; i) {
int j = pi[i-1];
while (j > 0 && s[i] != s[j]) {
j = pi[j-1];
}
if (s[i] == s[j]) {
j;
}
pi[i] = j;
}
return pi;
}
// 计算最多重复次数
int max_repeats(const string& s) {
int n = s.size();
if (n == 0) return 0;
vector<int> pi = compute_prefix(s);
int len = n - pi.back(); // 可能的最小重复子串长度
// 如果能整除,说明可以由len长度的子串重复构成
if (n % len == 0) {
return n / len;
} else {
return 1;
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
string s;
while (cin >> s) {
if (s == ".") break; // 输入结束标志
cout << max_repeats(s) << endl;
}
return 0;
}
这里空空如也







有帮助,赞一个