I was reading about Longest Palindrome Subsequence algorithm and came across this video :- Video
And also came across this blog for the dynamic program code for this problem. Ajeet Singh
Here is the code from the above link :-
public static int getLongestPalindromicSubSequenceSize(String source){
int n = source.length();
int[][] LP = new int[n][n];
//All sub strings with single character will be a plindrome of size 1
for(int i=0; i < n; i++){
LP[i][i] = 1;
}
//Here gap represents gap between i and j.
for(int gap=1;gap<n;gap++){ //-------> 1
for(int i=0;i<n-gap;i++ ){// --------> 2
int j=i+gap; // ---------> 3
if(source.charAt(i)==source.charAt(j) && gap==1)
LP[i][j]=2;
else if(source.charAt(i)==source.charAt(j))
LP[i][j]=LP[i+1][j-1]+2;
else
LP[i][j]= Math.max(LP[i][j-1], LP[i+1][j]);
}
}
return LP[0][n-1];
}
In the above code I have marked three lines as 1, 2 and 3. I am unable to understand those to loops . My doubts :-
1)In the first loop he has initialized an integer called gap to 1 . Why did he initialize it to 1 and why not 0 ?
2) In the second for loop , i<n-gap
, why did he do that ?
3) int j=i+gap
why this again?
I am new to Java and I have a problem in understanding them . Kindly can anyone please explain these three lines of code .
Thanks