编辑代码

function getLongestCommonSequence(wordA, wordB) {
    const lengthA = wordA.length;
    const lengthB = wordB.length;

    if (lengthA === 0 || lengthB === 0) {
        console.log("Please check words you entered.");
        return { length: -1, sequence: "" };
    }

    const dpArray = new Array(lengthA + 1).fill(0).map(() => new Array(lengthB + 1).fill(0));

    for (let i = 1; i <= lengthA; i++) {
        for (let j = 1; j <= lengthB; j++) {
            if (wordA[i - 1].toUpperCase() === wordB[j - 1].toUpperCase()) {
                dpArray[i][j] = dpArray[i - 1][j - 1] + 1;
            } else {
                dpArray[i][j] = Math.max(dpArray[i - 1][j], dpArray[i][j - 1]);
            }
        }
    }

    let i = lengthA;
    let j = lengthB;
    const sequence = [];
    while (i > 0 && j > 0) {
        if (wordA[i - 1].toUpperCase() === wordB[j - 1].toUpperCase()) {
            sequence.unshift(wordA[i - 1].toUpperCase());
            i--;
            j--;
        } else if (dpArray[i - 1][j] > dpArray[i][j - 1]) {
            i--;
        } else {
            j--;
        }
    }

    return { length: dpArray[lengthA][lengthB], sequence: sequence.join('') };
}

const result1 = getLongestCommonSequence("MIGRATION", "Migrapion");
console.log("The length of the longest common sequence is", result1.length);
console.log(result1.sequence);

const result2 = getLongestCommonSequence("Fish", "Hist");
console.log("The length of the longest common sequence is", result2.length);
console.log(result2.sequence);

const result3 = getLongestCommonSequence("Admin", "user");
console.log("The length of the longest common sequence is", result3.length);
console.log(result3.sequence);