1 条题解

  • 0
    @ 2026-11-2 10:56:24

    密码子串(Password) 题解

    思路分析

    按题目要求使用对应数据结构与算法模拟/递推求解,注意数据范围边界与时间复杂度。

    参考代码

    #include <iostream>
    #include <string>
    #include <vector>
    using namespace std;
    
    int main() {
        ios::sync_with_stdio(false);
        cin.tie(nullptr);
        string s;
        if (!(cin >> s)) return 0;
        int n = (int)s.size();
        if (n < 3) {
            cout << "Just a legend\n";
            return 0;
        }
        vector<int> pi(n, 0);
        vector<char> has(n + 1, 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;
            if (i < n - 1) has[pi[i]] = 1;
        }
        int len = pi[n - 1];
        while (len > 0) {
            if (has[len]) {
                cout << s.substr(0, len) << "\n";
                return 0;
            }
            len = pi[len - 1];
        }
        cout << "Just a legend\n";
        return 0;
    }
    
    • 1

    信息

    ID
    8575
    时间
    2000ms
    内存
    256MiB
    难度
    (无)
    标签
    递交数
    0
    已通过
    0
    上传者