编辑代码

#include <iostream>
#include <string>

using namespace std;

int getLongestCommonSequence(string wordA, string wordB, string *sequence) {
   
    int lengthA = wordA.length();
    int lengthB = wordB.length();

    if (0 == lengthA || 0 == lengthB) {
        cout << "Please check word you entered." << endl;
        return -1;
    }
    int **dpArray = new int*[lengthA];
    for (int i = 0; i < lengthA; ++i) {
        dpArray[i] = new int[lengthB];
    }

    int maxLength = 0;
    for (int i = 0; i < lengthA; ++i)
    {
        for (int j = 0; j < lengthB; ++j)
        {
            if (wordA.at(i) == wordB.at(j)) {
                dpArray[i][j] = 1;
                if (i > 0 && j > 0) {
                    dpArray[i][j] += dpArray[i - 1][j - 1];
                }
                if (maxLength < dpArray[i][j]){
                    sequence->push_back(wordA.at(i));
                    maxLength = dpArray[i][j];
                }
         
            }
            else {
                dpArray[i][j] = 0;

                if (i > 0) {
                    dpArray[i][j] = dpArray[i - 1][j];
                }
                if (j > 0 && dpArray[i][j] < dpArray[i][j - 1]) {
                    dpArray[i][j] = dpArray[i][j - 1];
                }
            }

        }    
    }
    maxLength = dpArray[lengthA - 1][lengthB - 1];
    for (size_t i = 0; i < lengthA; i++)
    {
        delete dpArray[i];
    }
    delete [] dpArray;
    return maxLength;
}

int main() {
    string wordA = "";
    string wordB = "";

    while (true)
    {
        cout << "Please enter word A: " << endl;
        cin >> wordA;
        if (wordA == "-1") {
            break;
        }
        cout << "Please enter word B: " << endl;
        cin >> wordB;
        string longestCommonSequence = "";
        int length = getLongestCommonSequence(wordA, wordB, &longestCommonSequence);
        cout << "The length of the longest common sequence is " << length << endl;
        cout << longestCommonSequence << endl; 
    }
}