最长重复子串

#include <iostream>
#include <string>
using namespace std;

// 简单模式匹配,判断从主串s的pos位置开始,是否有与子串sub匹配的子串
bool simpleMatch(const string& s, const string& sub, int pos) {
    int i = pos, j = 0;
    while (i < s.size() && j < sub.size()) {
        if (s[i] == sub[j]) {
            i++;
            j++;
        } else {
            break;
        }
    }
    return j == sub.size(); // 若j等于sub长度,说明完全匹配
}

int main() {
    string s;
    cout << "请输入字符串: ";
    cin >> s;

    int maxLen = 0;      // 最长重复子串的长度
    int startIndex = 0;  // 最长重复子串的起始下标

    // 外层循环:子串的起始位置
    for (int i = 0; i < s.size(); i++) {
        // 内层循环:子串的长度
        for (int len = 1; len <= s.size() - i; len++) {
            string sub = s.substr(i, len); // 截取子串
            // 从i + 1位置开始检查是否有重复子串
            for (int k = i + 1; k + len <= s.size(); k++) {
                if (simpleMatch(s, sub, k)) {
                    // 若找到更长的重复子串,更新maxLen和startIndex
                    if (len > maxLen) {
                        maxLen = len;
                        startIndex = i;
                    }
                    break; // 找到重复即可,跳出当前子串的重复检查
                }
            }
        }
    }

    if (maxLen > 0) {
        cout << "第一个最长重复子串的起始下标为: " << startIndex << endl;
        cout << "长度为: " << maxLen << endl;
        cout << "子串为: " << s.substr(startIndex, maxLen) << endl;
    } else {
        cout << "字符串中没有重复子串" << endl;
    }

    return 0;
}

 

posted @ 2025-11-05 13:44  ouyeye  阅读(6)  评论(0)    收藏  举报