A subsequence is a group of characters chosen from a list while maintaining their order. For instance, the subsequenes of the string abc
are [a, b, c, ab, ac, bc, abc]
.
Now, I need to write a function to return all the palindromic subsequences from a given string in order. For instance, for the string acdapmpomp
, the output should be [a,c,d,p,m,o,aa,aca,ada,pmp,mm,mom,pp,ppp,pop,mpm,pmpmp]
.
My code is:
function getAllPalindromicSubsequences(str) {
var result = [];
for (let i = 0; i < str.length; i++) {
for (let j = i + 1; j < str.length + 1; j++) {
if (str.slice(i, j).split("").reverse().join("") == str.slice(i, j)){
result.push(str.slice(i, j));
}
}
}
return result;
}
console.log(getAllPalindromicSubsequences("acdapmpomp"));
But this produces the following output:
[
'a', 'c', 'd',
'a', 'p', 'pmp',
'm', 'p', 'o',
'm', 'p'
]
What is the mistake I am making? And what should be the correct code?