class Solution {
// idea: longest palindromic subsequence will be length of LCS
public int longestPalindromeSubseq
(String s
) { int n = s.length();
// reverse the string and stroe it in new string
String s2
= new StringBuilder
(s
).
reverse().
toString(); int m = s2.length();
// step-1 create a matrix
// t[i][j] = LCS of first i chars of s and first j chars of reversed string
int[][] t = new int[n+1][m+1];
// step-2 initialise the matrix with base condition
for(int i=0; i<n+1; i++)
{
for(int j=0; j<m+1; j++)
{
// string length is 0, NO LCS found
if(i == 0 || j == 0)
t[i][j] = 0;
}
}
// step-3 iterative code to find length of LCS
for(int i=1; i<n+1; i++)
{
for(int j=1; j<m+1; j++)
{
// characters match
if(s.charAt(i-1) == s2.charAt(j-1))
t[i][j] = 1 + t[i-1][j-1];
// characters do not match
else
t
[i
][j
] = Math.
max(t
[i
-1][j
], t
[i
][j
-1]); }
}
// The bottom-right cell contains the length of LPS
int lcsLength = t[n][m];
return lcsLength;
}
}