Created
April 8, 2019 07:18
-
-
Save rix1/ac9fd3fd35956c9c2ab8170662b3201b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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