Skip to content

Commit 1bf0fe0

Browse files
committed
LPS algorithm
1 parent d7a5dbe commit 1bf0fe0

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
package DynamicProgramming;
2+
import java.lang.*;
3+
import java.io.*;
4+
import java.util.*;
5+
6+
/**
7+
* @author Matteo Messmer https://github.com/matteomessmer
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+
private static String LPS(String original) {
22+
StringBuilder reverse = new StringBuilder();
23+
reverse.append(original);
24+
reverse = reverse.reverse();
25+
return recursiveLPS(original, reverse);
26+
}
27+
28+
private static String recursiveLPS(String original, String reverse) {
29+
String bestResult = ""
30+
31+
//no more chars, then return empty
32+
if(original.length() == 0 || reverse.length() == 0) {
33+
bestResult = "";
34+
} else {
35+
36+
//if the last chars match, then remove it from both strings and recur
37+
if(original.charAt(original.length() - 1) == reverse.charAt(reverse.length() - 1)) {
38+
String bestSubResult = recursiveLPS(original.substring(0, original.length() - 1), reverse.substring(0, reverse.length() - 1));
39+
40+
bestResult = reverse.charAt(reverse.length() - 1) + bestSubResult;
41+
} else {
42+
//otherwise (1) ignore the last character of reverse, and recur on original and updated reverse again
43+
//(2) ignore the last character of original and recur on the updated original and reverse again
44+
//then select the best result from these two subproblems.
45+
46+
String bestSubResult1 = recursiveLPS(original, reverse.substring(0, reverse.length() - 1));
47+
String bestSubResult2 = recursiveLPS(original.substring(0, original.length() - 1), reverse);
48+
if(bestSubResult1.length()>bestSubResult2.length()) {
49+
bestResult = bestSubResult1;
50+
} else {
51+
bestResult = bestSubResult2;
52+
}
53+
}
54+
}
55+
56+
return bestResult;
57+
}
58+
}

0 commit comments

Comments
 (0)