-
Notifications
You must be signed in to change notification settings - Fork 985
/
Copy pathlongest_palindromic_substring.cpp
51 lines (50 loc) · 1.17 KB
/
longest_palindromic_substring.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
#include <bits/stdc++.h>
using namespace std;
string longestPalindrome(string s) {
int n=s.length();
int dp[n][n];
int end=0;
int start=0;
string res="";
for(int g=0;g<n;g++){
int i=0;
int j=g;
while(j<n){
if(g==0){
dp[i][j]=true;
}
else if(g==1){
if(s[i]==s[j]){
dp[i][j]=true;
}
else{
dp[i][j]=false;
}
}else{
if(s[i]==s[j] && dp[i+1][j-1]){
dp[i][j]=true;
}
else{
dp[i][j]=false;
}
}
if(dp[i][j] && j-i > end-start){
end=j;
start=i;
}
i++;
j++;
}
}
return s.substr(start,end-start+1);
}
int main()
{
int t;
cin>>t;
while(t--){
string S;
cin>>S;
cout << longestPalindrome(S) << endl;
}
}