Skip to content

Commit 020eb8b

Browse files
authored
Create Longest Palindromic Subsequence.java
1 parent b18576d commit 020eb8b

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

Longest Palindromic Subsequence.java

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
GFG
2+
Longest Palindromic Subsequence
3+
4+
5+
6+
7+
class Solution
8+
{
9+
public int longestPalinSubseq(String S)
10+
{
11+
//code here
12+
StringBuilder str = new StringBuilder(S);
13+
String s1 = S;
14+
String s2 = str.reverse().toString();
15+
int n = S.length();
16+
int dp[][] = new int[n+1][n+1];
17+
18+
19+
for( int i =0 ; i<=n ;i++)
20+
{
21+
for( int j =0; j<=n;j++)
22+
{
23+
if(i==0 || j==0)
24+
dp[i][j] =0;
25+
26+
else if( s1.charAt(i-1)==s2.charAt(j-1) )
27+
dp[i][j] = 1+dp[i-1][j-1];
28+
29+
else
30+
dp[i][j] = Math.max(dp[i-1][j] , dp[i][j-1]);
31+
}
32+
}
33+
34+
return dp[n][n];
35+
}
36+
}

0 commit comments

Comments
 (0)