dp
with dimensions [s.length()][s.length()][26]
to store the longest palindromic subsequences.s
by using two nested loops, with i
going from s.length() - 1
to 0
and j
going from i + 1
to s.length() - 1
.s[i...j]
, iterate over all possible previous characters k
from 0
to 25
.s[i]
equals s[j]
and s[i]
is not equal to the character represented by k
, update dp[i][j][s[i] - 'a']
to be the maximum of its current value and dp[i + 1][j - 1][k] + 2
.dp[i][j][k]
to be the maximum of dp[i][j][k]
, dp[i + 1][j][k]
, and dp[i][j - 1][k]
to inherit the previous maximum length wrapped by character k
.dp
array, the answer is the maximum value in dp[0][s.length() - 1]
.