forked from Red-0111/Anything-Repo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongest_Palindromic_Subsequence.cpp
More file actions
66 lines (53 loc) · 1.25 KB
/
Longest_Palindromic_Subsequence.cpp
File metadata and controls
66 lines (53 loc) · 1.25 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <bits/stdc++.h>
using namespace std;
// problem link : https://practice.geeksforgeeks.org/problems/longest-palindrome-in-a-string1956/1
void printSubStr(
string str, int low, int high)
{
for (int i = low; i <= high; ++i)
cout << str[i];
}
int longestPalSubstr(string str)
{
int n = str.size();
bool dp[n][n];
memset(dp, 0, sizeof(dp));
int maxLength = 1;
for (int i = 0; i < n; ++i)
dp[i][i] = true;
int start = 0;
for (int i = 0; i < n - 1; ++i)
{
if (str[i] == str[i + 1])
{
dp[i][i + 1] = true;
start = i;
maxLength = 2;
}
}
for (int k = 3; k <= n; ++k)
{
for (int i = 0; i < n - k + 1; ++i)
{
int j = i + k - 1;
if (dp[i + 1][j - 1] && str[i] == str[j])
{
dp[i][j] = true;
if (k > maxLength)
{
start = i;
maxLength = k;
}
}
}
}
cout << "Longest palindrome substring is: ";
printSubStr(str, start, start + maxLength - 1);
return maxLength;
}
int main()
{
string str = "babad";
cout << longestPalSubstr(str);
return 0;
}