javascriptnode.jslcs

Longest Common Substring (more than 2 arguments)


I have seen the solution for LCS 2 strings. Below is the code. I am curious how can I change it so that it can solve properly when more than 2 strings are given.

I would appreciate any help or resource that can be useful Thank you.

const printLCS = (a, b) => {
    let m = a.length;
    let n = b.length;
    let lcs = new Array(m + 1);
    let lcsLen = 0;
    let row = 0, col = 0;

    for (let i = 0; i <= m; i++) {
        lcs[i] = Array(n + 1);
        for (let j = 0; j <= n; j++) {
            lcs[i][j] = 0;
            if (i == 0 || j == 0) {
                lcs[i][j] = 0;
            } else if (a[i - 1] == b[j - 1]) {
                lcs[i][j] = lcs[i - 1][j - 1] + 1;
                if (lcsLen < lcs[i][j]) {
                    lcsLen = lcs[i][j];
                    row = i;
                    col = j;
                }
            } else {
                lcs[i][j] = 0;
            }
        }
    }

    if (lcsLen == 0) {
        console.log("No Common Substring");
        return;
    }

    let resStr = "";

    while (lcs[row][col] != 0) {
        resStr = a[row - 1] + resStr;
        --lcsLen;
        row--;
        col--;
    }
    console.log(resStr);
}

const myArgs = process.argv.slice(2);
printLCS(myArgs[0], myArgs[1]);

const onErr = (err) => {
    console.log(err);
    return 1;
}


Solution

  • Although, it might be a bit too late to answer now, I think, I might have found the issue you have.

    It is with the function call.

    printLCS(myArgs[0],myArgs[1]); 
    

    You are specifying the third and fourth argument, while perhaps a better way would be to spread it all like this.

    printLCS(...myArgs);