Skip to content

Instantly share code, notes, and snippets.

@rix1
Created April 8, 2019 07:18
Show Gist options
  • Save rix1/ac9fd3fd35956c9c2ab8170662b3201b to your computer and use it in GitHub Desktop.
Save rix1/ac9fd3fd35956c9c2ab8170662b3201b to your computer and use it in GitHub Desktop.
tests = [["ABAZDC", "BACBAD"], ["AA", "AAAA"], ["AGGTAB", "GXTXAYB"]];
function findCommon(a, b) {
arrB = [...b];
return [...a].filter((c, index) => {
if (!arrB.includes(c)) {
return false;
}
const match = arrB.indexOf(c, Math.min(index, arrB.length - 1));
if (match !== -1) {
return true;
}
});
}
function longestCommon(s1, s2) {
const maxLength = Math.min(s1.length, s2.length);
f1 = findCommon(s1, s2).join("");
f2 = findCommon(s2, s1).join("");
const long = Math.max(f1.length, f2.length) === f1.length ? f1 : f2;
const short = long === f1 ? f2 : f1;
return long.length <= maxLength ? long : short;
}
tests.map((pair, index) => {
console.log("Winner", index, longestCommon(pair[0], pair[1]));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment