Search This Blog

2023/05/26

Longest common child String

 function commonChild(string1, string2) {

var n = string1.length
const dp = Array.from({ length: n + 1 }, () => Array(n + 1).fill(0));

for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
if (string1[i] == string2[j]) {
dp[i + 1][j + 1] = dp[i][j] + 1
} else {
let r1 = dp[i + 1][j]
let r2 = dp[i][j + 1]

dp[i + 1][j + 1] = Math.max(r1, r2)
}
}
}
console.log("dp:",dp)

let commonChildLength = dp[n][n]
let commonChildString = ""

let i = n;
let j = n;
while (i > 0 && j > 0) {
if (string1[i - 1] == string2[j - 1]) {
commonChildString = string1[i - 1] + commonChildString
i--
j--
} else if (dp[i][j - 1] >= dp[i - 1][j]) {
j--
} else {
i--
}
}

return { "length": commonChildLength, "string": commonChildString }

//return commonChildLength
}


const string1 = "HARRY";
const string2 = "SALLY";
const result = commonChild(string1, string2);
console.log("Result:", result); // Output: "AY"

No comments:

Post a Comment