1
+ package test ;
2
+ import java .lang .*;
3
+ import java .io .*;
4
+ import java .util .*;
5
+
6
+ /**
7
+ * Algorithm explanation https://www.educative.io/edpresso/longest-palindromic-subsequence-algorithm
8
+ */
9
+ public class LongestPalindromicSubsequence {
10
+ public static void main (String [] args ) {
11
+ String a = "BBABCBCAB" ;
12
+ String b = "BABCBAB" ;
13
+
14
+ String aLPS = LPS (a );
15
+ String bLPS = LPS (b );
16
+
17
+ System .out .println (a + " => " + aLPS );
18
+ System .out .println (b + " => " + bLPS );
19
+ }
20
+
21
+ public static String LPS (String original ) throws IllegalArgumentException {
22
+ StringBuilder reverse = new StringBuilder (original );
23
+ reverse = reverse .reverse ();
24
+ return recursiveLPS (original , reverse .toString ());
25
+ }
26
+
27
+ private static String recursiveLPS (String original , String reverse ) {
28
+ String bestResult = "" ;
29
+
30
+ //no more chars, then return empty
31
+ if (original .length () == 0 || reverse .length () == 0 ) {
32
+ bestResult = "" ;
33
+ } else {
34
+
35
+ //if the last chars match, then remove it from both strings and recur
36
+ if (original .charAt (original .length () - 1 ) == reverse .charAt (reverse .length () - 1 )) {
37
+ String bestSubResult = recursiveLPS (original .substring (0 , original .length () - 1 ), reverse .substring (0 , reverse .length () - 1 ));
38
+
39
+ bestResult = reverse .charAt (reverse .length () - 1 ) + bestSubResult ;
40
+ } else {
41
+ //otherwise (1) ignore the last character of reverse, and recur on original and updated reverse again
42
+ //(2) ignore the last character of original and recur on the updated original and reverse again
43
+ //then select the best result from these two subproblems.
44
+
45
+ String bestSubResult1 = recursiveLPS (original , reverse .substring (0 , reverse .length () - 1 ));
46
+ String bestSubResult2 = recursiveLPS (original .substring (0 , original .length () - 1 ), reverse );
47
+ if (bestSubResult1 .length ()>bestSubResult2 .length ()) {
48
+ bestResult = bestSubResult1 ;
49
+ } else {
50
+ bestResult = bestSubResult2 ;
51
+ }
52
+ }
53
+ }
54
+
55
+ return bestResult ;
56
+ }
57
+ }
0 commit comments