初学js,拿个lcs问题练练手:
/**
* Created by fhqplzj on 2017/7/15.
*/
function lcs(s1, s2) {
var m = s1.length, n = s2.length;
var dp = new Array(m + 1);
for (var i = 0; i < dp.length; i++) {
dp[i] = new Array(n + 1);
dp[i][0] = 0;
}
for (var j = 1; j < dp[0].length; j++) {
dp[0][j] = 0;
}
for (i = 1; i < dp.length; i++) {
var c1 = s1.charAt(i - 1);
for (j = 1; j < dp[0].length; j++) {
var c2 = s2.charAt(j - 1);
if (c1 === c2) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
return dp[m][n];
}
console.log(lcs('abc', 'bcd'));