-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlongestPalindromicSubstring.cpp
More file actions
57 lines (50 loc) · 1.03 KB
/
Copy pathlongestPalindromicSubstring.cpp
File metadata and controls
57 lines (50 loc) · 1.03 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
#include <cstring>
#include <iostream>
using namespace std;
string longestPalindromicSubstring(string s)
{
if(s.empty()||s=="")
return "";
int len=s.length();
int start=0,maxlength=1;
bool dp[n][n];
memset(dp,0,sizeof(dp));
for(int i=0;i<len;i++)
dp[i][i]=true;
for(int i=0;i<len-1;i++)
if(s[i]==s[i+1])
{
dp[i][i+1]=true;
start = i;
maxlength=2;
}
for(int k=3;k<=len;k++)
{
for(int i=0;i<=len-k;i++)
{
int j=i+k-1;
if(s[i]==s[j]&&dp[i+1][j-1])
{
dp[i][j]=true;
if(maxlength<k)
{
start=i;
maxlength=k;
}
}
}
}
return s.substr(start,maxlength);
}
int main()
{
int cases;
cin>>cases;
while(cases--)
{
string str;
cin>>str;
cout<<longestPalindromicSubstring(str)<<endl;
}
return 0;
}