Not a member of GistPad yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- // idea: longest palindromic subsequence will be length of LCS
- int n = s.length();
- // reverse the string and stroe it in new string
- 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
- }
- }
- // The bottom-right cell contains the length of LPS
- int lcsLength = t[n][m];
- return lcsLength;
- }
- }
RAW Paste Data
Copied
