编辑代码

#include <iostream>
#include <string>
#include <set>

using namespace std;

int getLongestCommonSubstringSet(string wordA, string wordB, set<string> *subStringSet) {
   
    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 curMaxLen = 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 (curMaxLen < dpArray[i][j]) {
                    curMaxLen = dpArray[i][j];
                    subStringSet->clear();
                    subStringSet->insert(wordA.substr(i + 1 - curMaxLen, curMaxLen));
                }
                else if (curMaxLen == dpArray[i][j]) {
                    subStringSet->insert(wordA.substr(i + 1 - curMaxLen, curMaxLen));
                }
            }
            else {
                dpArray[i][j] = 0;
            }

        }    
    }
    for (size_t i = 0; i < lengthA; i++)
    {
        delete dpArray[i];
    }
    delete [] dpArray;
    return curMaxLen;
}
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;
        set<string> longestCommonSubstringSet;
        int length = getLongestCommonSubstringSet(wordA, wordB, &longestCommonSubstringSet);
        cout << "The length of the longest common substring is " << length << endl;
        for (set<string>::iterator i = longestCommonSubstringSet.begin(); 
             i != longestCommonSubstringSet.end(); ++i)
        {
            cout << *i << endl;
        }
    } 
}