forked from iiitu-force/Hacktoberfest-2021
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Longest Palindromic Subsequence.java
45 lines (28 loc) · 1.06 KB
/
Longest Palindromic Subsequence.java
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
//Longest Palindromic Subsequence
import java.util.Arrays;
public class Main {
static class Longest_Palindromic_Subsequence{
static int longest_palindromic_subsequence(String s,int startIndex,int endIndex)
{
if(startIndex>endIndex)
{
return 0;
}
if(startIndex==endIndex) {
return 1;
}
int c1=0;
if(s.charAt(startIndex)==s.charAt(endIndex)) {
c1 = 2+ longest_palindromic_subsequence(s, startIndex + 1, endIndex - 1);
}
int c2 = 0 + longest_palindromic_subsequence(s, startIndex, endIndex - 1);
int c3 = 0 + longest_palindromic_subsequence(s, startIndex + 1, endIndex);
return Math.max(c1, Math.max(c2, c3));
}
}
public static void main(String[] args) {
String str="ELRMENMET";
System.out.print("Longest Palindromic Subsequence: ");
System.out.println(Longest_Palindromic_Subsequence.longest_palindromic_subsequence(str,0,str.length()-1));
}
}