Public
Edited
May 6, 2023
Paused
Insert cell
Insert cell
lcsLength("lorem ipsum dolor", "lorem dolor")
Insert cell
lcsString("lorem ipsum dolor", "lorem losum dolor")
Insert cell
function lcsLength(text1, text2) {
// Base case: if either text is empty, the LCS has length 0
if (text1.length === 0 || text2.length === 0) {
return 0;
}

// If the last characters of the texts match, the LCS includes the last character
if (text1[text1.length - 1] === text2[text2.length - 1]) {
return 1 + lcsLength(text1.slice(0, -1), text2.slice(0, -1));
}

// If the last characters of the texts don't match, the LCS is the maximum of the LCS of the
// first text and the second text with the last character removed
return Math.max(lcsLength(text1.slice(0, -1), text2), lcsLength(text1, text2.slice(0, -1)));
}


Insert cell
function lcsString(text1, text2) {
// Base case: if either text is empty, the LCS is the empty string
if (text1.length === 0 || text2.length === 0) {
return '';
}

// If the last characters of the texts match, the LCS includes the last character
if (text1[text1.length - 1] === text2[text2.length - 1]) {
return lcsString(text1.slice(0, -1), text2.slice(0, -1)) + text1[text1.length - 1];
}

// If the last characters of the texts don't match, the LCS is the maximum of the LCS of the
// first text and the second text with the last character removed
const lcs1 = lcsString(text1.slice(0, -1), text2);
const lcs2 = lcsString(text1, text2.slice(0, -1));
return lcs1.length > lcs2.length ? lcs1 : lcs2;
}
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more