E. Nearly Shortest Repeating Substring

https://codeforces.com/contest/1950/problem/E

题意:给定一个长度为n的字符串s,现在要找一个n的最长的子串c,c重复若干次后,长度跟s一样,并且c跟s不相同的字符数量不能超过一个。问c的最短长度是多少?

思路:暴力破解即可,求出所有c可能的长度,然后判断当前长度是否满足条件。判断的方法就是看不相同的字符的数量,大于1说明该长度不行。有个注意的点是要拿其他位置的字符跟当前位置字符比较时,如果字符只有两种,并且当前字符跟其他位置所有字符都不相同,那么不相同的字符数量应该是一个,而不是f - 1个(f是当前考虑的长度)

inline void solve() {
    int n;
    cin >> n;

    string s;
    cin >> s;

    set<int> factors;
    for (int i = 1; 1ll * i * i <= n; ++i) {
        if (n % i == 0) {
            factors.insert(i);
            factors.insert(n / i);
        }
    }

    for (auto f : factors) {
        int dif = 0;
        for (int i = 0; i < f && dif < 2; ++i) {
            int cur = 0;
            array<int, 26> cnt = {};
            cnt[s[i] - 'a'] ++;
            int g = 0;
            for (int j = i + f; j < n; j += f) {
                cnt[s[j] - 'a'] ++;
                g += s[j] != s[i];
            }
            int nums = 0;
            for (int j = 0; j < 26; ++j){
                nums += cnt[j] > 0;
            }
            if (nums > 2) {
                dif = 3;
                break;
            }
            else {
                g = min(g, n / f - g);
            }
            dif += g;
        }
        if (dif < 2) {
            cout << f << '\n';
            return;
        }
    }

    cout << n << '\n';
}
posted @ 2025-06-09 10:12  _Yxc  阅读(7)  评论(0)    收藏  举报