-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathpalinsubstring(dp).cpp
More file actions
39 lines (39 loc) · 878 Bytes
/
Copy pathpalinsubstring(dp).cpp
File metadata and controls
39 lines (39 loc) · 878 Bytes
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
class Solution {
public:
string longestPalindrome(string s) {
string st="";
int n=s.size();
int dp[n+1][n+1];
memset(dp,0,sizeof(dp));
for(int i=0;i<n;i++)
dp[i][i]=1;
int start=0,x=1;
for(int i=0;i<n-1;i++)
{
if(s[i+1]==s[i])
{
dp[i][i+1]=1;
start=i;
x=2;
}
}
for(int gap=3;gap<=n;gap++)
{
for(int i=0;i<n-gap+1;i++)
{
int j=i+gap-1;
if(dp[i+1][j-1]==1 && s[i]==s[j])
{
dp[i][j]=1;
if(x<gap)
{
x=gap;
start=i;
}
}
}
}
st=s.substr(start,x);
return st;
}
};