编辑代码

#include <iostream>
#include <cstring> 

using namespace std;

const int MAX_SIZE = 1000; // 你可以根据实际情况调整数组大小

int dp[MAX_SIZE + 1][MAX_SIZE + 1];

string longestCommonSubsequence(string text1, string text2) {
    int m = text1.length();
    int n = text2.length();

    // 将数组dp初始化为0
    memset(dp, 0, sizeof(dp));

    // 填充dp数组
    for (int i = 1; i <= m; ++i) {
        for (int j = 1; j <= n; ++j) {
            if (text1[i - 1] == text2[j - 1]) {
                dp[i][j] = dp[i - 1][j - 1] + 1;
            } else {
                dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
            }
        }
    }

    // 从dp数组中构造最长公共子序列
    int i = m, j = n;
    string lcs;
    while (i > 0 && j > 0) {
        if (text1[i - 1] == text2[j - 1]) {
            lcs = text1[i - 1] + lcs;
            i--;
            j--;
        } else if (dp[i - 1][j] > dp[i][j - 1]) {
            i--;
        } else {
            j--;
        }
    }

    return lcs;
}

int main() {
    string text1 = "abcde";
    string text2 = "ace";

    string result = longestCommonSubsequence(text1, text2);

    cout << "Longest Common Subsequence: " << result << endl;

    return 0;
}