I've been working on creating a function that can identify the longest palindrome subsequence within a given string. After experimenting with dynamic programming, I came up with the code snippet below:
function findLongestPalindrome(str) {
let length = str.length;
let memoization = Array(length);
for (let i = 0; i < length; i++) {
memoization[i] = Array(length);
memoization[i][i] = 1;
}
for (let cl = 2; cl <= length; cl++) {
for (let i = 0; i < length - cl + 1; i++) {
let j = i + cl - 1;
if (str[i] === str[j] && cl === 2)
memoization[i][j] = 2;
else if (str[i] === str[j])
memoization[i][j] = memoization[i + 1][j - 1] + 2;
else
memoization[i][j] = Math.max(memoization[i][j - 1], memoization[i + 1][j]);
}
}
return memoization[0][length - 1];
}
Despite my efforts, this implementation isn't consistently efficient across all test cases and the Time and Space Complexity needs to be optimized further. I've been stuck on this problem for some time now and can't seem to pinpoint the issue. If anyone could provide insight on what might be going wrong and suggest potential solutions, it would be greatly appreciated.