Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit dc09afc

Browse files
authored
Create Leetcode_516_Longest_Palindromic_SubSequence.java
1 parent c6b45f4 commit dc09afc

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
public static void display_1D(int[] arr)
2+
{
3+
for (int ele : arr)
4+
{
5+
System.out.print(ele + "\t");
6+
}
7+
System.out.println();
8+
}
9+
public static void display_2D(int[][] arr)
10+
{
11+
for (int[] ar : arr)
12+
{
13+
display_1D(ar);
14+
}
15+
System.out.println();
16+
}
17+
18+
public static int Leetcode_516_Longest_Pallindromic_SubSequence_Tabulation(String str, int si, int ei, int[][] dp, boolean[][] isPalindrome)
19+
{
20+
int n=str.length();
21+
for(int gap = 0; gap < n; gap++)
22+
{
23+
for(si = 0; si < n - gap; si++)
24+
{
25+
ei = si + gap;
26+
27+
if(isPalindrome[si][ei])
28+
{
29+
dp[si][ei] = ei-si+1;
30+
continue;
31+
}
32+
33+
int len=0;
34+
if(str.charAt(si) == str.charAt(ei))
35+
{
36+
len = dp[si+1][ei-1] + 2;
37+
}
38+
else
39+
{
40+
len = Math.max(dp[si+1][ei], dp[si][ei-1]);
41+
}
42+
43+
dp[si][ei] = len;
44+
}
45+
}
46+
47+
return dp[0][str.length()-1];
48+
}
49+
50+
public static void Leetcode_516_Longest_Pallindromic_SubSequence()
51+
{
52+
String str = "geeksforgeeks";
53+
int n = str.length();
54+
int si = 0, ei = n - 1;
55+
int[][] dp = new int[n][n];
56+
57+
boolean[][] isPalindrome = is_Pallindrome_SubString(str);
58+
System.out.println("Tabulation :- " + Leetcode_516_Longest_Pallindromic_SubSequence_Tabulation(str, si, ei, dp, isPalindrome));
59+
display_2D(dp);
60+
}

0 commit comments

Comments
 (0)