-
Notifications
You must be signed in to change notification settings - Fork 293
/
longestPalindrome.cpp
62 lines (53 loc) · 1.22 KB
/
longestPalindrome.cpp
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
#include <bits/stdc++.h>
using namespace std;
string longestPalindrome(string s) {
int n=s.length();
vector<vector<bool>>dp(n, vector<bool>(n));
for(int i=n-1;i>=0;i--)
{
for(int j=i;j<n;j++)
{
if(i==j)
{
dp[i][j] = true;
}
else if(s[i]==s[j])
{
dp[i][j] = (i+1<j-1)?dp[i+1][j-1]:true;
}
else
dp[i][j] =0;
}
}
int maxx = 0;
int ind = -1;
int jnd = -1;
for(int i=0;i<n;i++)
{
for(int j=i;j<n;j++)
{
if(dp[i][j] && (j-i+1)>maxx)
{
maxx = j-i+1;
ind = i;
jnd = j;
}
}
}
//cout<<ind<<" "<<jnd<<endl;
//return "";
return string(s.begin()+ind, s.begin()+jnd+1);
}
int main()
{
int t;
cin>>t;
while(t--)
{
string s;
cin>>s;
string ans = longestPalindrome(s);
cout<<ans<<endl;
}
return 0;
}