Skip to content

Commit 28d89c2

Browse files
authored
Merge pull request #24 from badshah008/main
Length of Longest Palindromic Subsequence
2 parents b7c3a68 + 1f36f62 commit 28d89c2

1 file changed

+49
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
#include<bits/stdc++.h>
2+
using namespace std;
3+
4+
int findLPS(string s) {
5+
6+
int n = s.length();
7+
int dp[n][n];
8+
memset(dp, 0, sizeof(dp));
9+
10+
// Every single character is a palindrome itself, of length 1
11+
for (int i = 0; i < n; ++i)
12+
dp[i][i] = 1;
13+
14+
// Check every subsequence of length 2 and greater, upto length of the string
15+
for (int len = 2; len <= n; ++len) {
16+
17+
for (int i = 0; i <= n - len; ++i) {
18+
19+
int j = i + len - 1;
20+
21+
if (s[i] == s[j] && len == 2)
22+
dp[i][j] = 2;
23+
else if (s[i] == s[j])
24+
dp[i][j] = dp[i+1][j-1] + 2;
25+
else
26+
dp[i][j] = max(dp[i][j-1], dp[i+1][j]);
27+
}
28+
}
29+
30+
// Top-right corner cell will contain the length of LPS
31+
return dp[0][n-1];
32+
}
33+
34+
int main() {
35+
36+
string s;
37+
cout << "Enter the string : ";
38+
cin >> s;
39+
40+
int res = findLPS(s);
41+
cout << "Length of the Longest Palindromic Subsequence is : " << res << '\n';
42+
43+
return 0;
44+
}
45+
46+
/*
47+
~ Time Complexity : O(n^2)
48+
~ Space Complexity : O(n^2)
49+
*/

0 commit comments

Comments
 (0)