2.8 KiB
2.8 KiB
id | title | challengeType | forumTopicId |
---|---|---|---|
5e6dd1278e6ca105cde40ea9 | Longest common subsequence | 5 | 385271 |
Description
Instructions
Tests
tests:
- text: <code>lcs</code> should be a function.
testString: assert(typeof lcs == 'function');
- text: <code>lcs("thisisatest", "testing123testing")</code> should return a string.
testString: assert(typeof lcs("thisisatest", "testing123testing") == 'string');
- text: <code>lcs("thisisatest", "testing123testing")</code> should return <code>"tsitest"</code>.
testString: assert.equal(lcs("thisisatest", "testing123testing"), "tsitest");
- text: <code>lcs("ABCDGH", "AEDFHR")</code> should return <code>"ADH"</code>.
testString: assert.equal(lcs("ABCDGH", "AEDFHR"), "ADH");
- text: <code>lcs("AGGTAB", "GXTXAYB")</code> should return <code>"GTAB"</code>.
testString: assert.equal(lcs("AGGTAB", "GXTXAYB"), "GTAB");
- text: <code>lcs("BDACDB", "BDCB")</code> should return <code>"BDCB"</code>.
testString: assert.equal(lcs("BDACDB", "BDCB"), "BDCB");
- text: <code>lcs("ABAZDC", "BACBAD")</code> should return <code>"ABAD"</code>.
testString: assert.equal(lcs("ABAZDC", "BACBAD"), "ABAD");
Challenge Seed
function lcs(a, b) {
}
Solution
function lcs(a, b) {
var aSub = a.substr(0, a.length - 1);
var bSub = b.substr(0, b.length - 1);
if (a.length === 0 || b.length === 0) {
return '';
} else if (a.charAt(a.length - 1) === b.charAt(b.length - 1)) {
return lcs(aSub, bSub) + a.charAt(a.length - 1);
} else {
var x = lcs(a, bSub);
var y = lcs(aSub, b);
return (x.length > y.length) ? x : y;
}
}