Skip to content

Instantly share code, notes, and snippets.

@abeltolu
Created November 24, 2019 15:14
Show Gist options
  • Save abeltolu/d48eae2c5bfb268e6744236e555b1fa6 to your computer and use it in GitHub Desktop.
Save abeltolu/d48eae2c5bfb268e6744236e555b1fa6 to your computer and use it in GitHub Desktop.
Get the longest subsequence between two strings
function getSubsequences(str){
let len = str.length, output, counter = 0, result = [];
for (let i = 1; i < Math.pow(2, len); i++) {
output = '';
for (var j = 0; j < len; j++) {
if (i & (1 << j)) {
output += str[j];
}
}
counter++;
result.push(output);
}
return result;
}
function getSubstrings(str){
let i, j, result = [];
for (i = 0; i < str.length; i++){
for (j = i+1; j < str.length + 1; j++){
result.push(str.slice(i, j));
}
}
return result;
}
function sortArrBylength(arr = []){
const result = arr.sort((a,b) => {
return b.length - a.length;
});
return result;
}
function longestSubsequence(x, y) {
// Write your code here
const subsequences = sortArrBylength(getSubsequences(x));
const substrings = getSubstrings(y);
let i, result;
for (i = 0; i < subsequences.length; i++){
if(substrings.includes(subsequences[i])){
result = subsequences[i];
break;
}
}
return result.length;
}
longestSubsequence('abcd', 'abdc');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment