Skip to content

Commit 1b0d831

Browse files
authoredApr 8, 2022
create Longest Palindromic Subsequence
1 parent fe76eba commit 1b0d831

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
 
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# Longest Palindromic Subsequence
2+
Question -> [Longest Palindromic Subsequence](https://leetcode.com/problems/longest-palindromic-subsequence/)
3+
4+
> **Logic**
5+
> We will be finding the longest common subsequence between string s and reverse of string s and this will give us Longest Palindromic Subsequence.
6+
7+
### Tabulation
8+
```java
9+
class Solution {
10+
public int longestPalindromeSubseq(String s) {
11+
StringBuilder sb = new StringBuilder(s);
12+
String rev = sb.reverse().toString();
13+
return lcs(s, rev);
14+
}
15+
private int lcs(String s, String t) {
16+
int n = s.length();
17+
int[][] dp = new int[n+1][n+1];
18+
// base case
19+
for(int i=0; i<=n; i++) {
20+
dp[i][0] = 0;
21+
dp[0][i] = 0;
22+
}
23+
for(int i=1; i<=n; i++) {
24+
for(int j=1; j<=n; j++) {
25+
if(s.charAt(i-1) == t.charAt(j-1)) {
26+
dp[i][j] = 1 + dp[i-1][j-1];
27+
} else {
28+
dp[i][j] = Math.max(dp[i-1][j],dp[i][j-1]);
29+
}
30+
}
31+
}
32+
return dp[n][n];
33+
}
34+
}
35+
```
36+
> `Time Complexity` : **O(N\*N)**
37+
> `Space Complexity` : **O(N\*N)**
38+
---
39+
Video Explanations -> [Longest Palindromic Subsequence](https://youtu.be/6i_T5kkfv4A?list=PLgUwDviBIf0qUlt5H_kiKYaNSqJ81PMMY)
40+
<hr>

0 commit comments

Comments
 (0)
Please sign in to comment.