forked from learning-zone/java-basics
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlongestPallindromicSubsequence.java
More file actions
49 lines (39 loc) · 977 Bytes
/
longestPallindromicSubsequence.java
File metadata and controls
49 lines (39 loc) · 977 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package DynamicProgramming;
import java.util.Arrays;
public class longestPallindromicSubsequence {
public static int longestPalinSubseq(String S) {
// code here
int n = S.length();
int[][] dp = new int[n][n];
for (int gap = 0; gap < n; gap++) {
for (int i = 0, j = gap; j < n; i++, j++) {
if (i == j) {
dp[i][j] = 1;
} else if (j - i == 1) {
if (S.charAt(i) == S.charAt(j)) {
dp[i][j] = 2;
} else {
dp[i][j] = 1;
}
} else {
if (S.charAt(i) == S.charAt(j)) {
dp[i][j] = 2 + dp[i + 1][j - 1];
} else {
dp[i][j] = Math.max(dp[i][j - 1], dp[i + 1][j]);
}
}
}
}
print(dp);
return dp[0][n - 1];
}
public static void print(int[][] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.println(Arrays.toString(arr[i]));
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(longestPalinSubseq("geekssgeek"));
}
}