abba => bb is palindromic. for (x)bb(y), x == y then, it is palindromic
var solution = s => {
const len = s.length;
let ans = s.substring(0, 1);
if (len <= 1) return s;
let memo = [];
console.log(memo);
for (let i = 0; i < len; i++) {
memo[i] = memo[i] || []
memo[i][i] = true; // length 1
// length 2
if (i + 1 < len && s.charAt(i) == s.charAt(i + 1)) {
memo[i][i + 1] = true;
ans = s.substring(i, i + 1 + 1);
}
}
console.log(memo);
// from length 3 to len
for (let i = 2; i < len; i++) {
for (let j = 0; j + i < len; j++) {
if (memo[j + 1][j + i - 1]) {
if (s.charAt(j) == s.charAt(j + i)) {
memo[j][j+i] = true;
if (ans.length < i + 1)
ans = s.substring(j, j + i + 1);
}
}
}
}
console.log(memo);
return ans;
}
var arr = ['a', '', 'aabb', 'abba', 'aabbccc', 'abababcbcbcb'];
for (const s of arr)
console.log(solution(s));
Time: O(N^2)
Space: O(N^2)