Skip to content

Commit 61802a6

Browse files
authored
Create (Using Binary search)Longest Palindromic Substring
1 parent 91ac962 commit 61802a6

File tree

1 file changed

+90
-0
lines changed

1 file changed

+90
-0
lines changed
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
//Author: Fuadul Hasan([email protected])
2+
//BSMRSTU,Gopalganj
3+
#include<bits/stdc++.h>
4+
using namespace std;int tc = 1;
5+
#define happy ios::sync_with_stdio(false);
6+
#define coding cin.tie(0);
7+
#define pb push_back
8+
#define mp make_pair
9+
#define ll long long
10+
#define pr pair<int, int>
11+
#define vpr vector<pr>
12+
#define vi std::vector<int>
13+
#define vll std::vector<ll>
14+
#define all(n) n.begin(),n.end()
15+
#define Test printf("Case %d: ",tc++);
16+
#define YES printf("YES\n");
17+
#define NO printf("NO\n");
18+
#define Yes printf("Yes\n");
19+
#define No printf("No\n");
20+
const int mod = 1e9 + 7;
21+
const ll Inf = (ll)2e18 + 5;
22+
const int N = 2e5 + 5;
23+
24+
bool is_paliondrom(string s){
25+
string rev = s;
26+
reverse(rev.begin(),rev.end());
27+
return s==rev;
28+
}
29+
30+
int good(int x,string s){
31+
int n = s.length();
32+
for(int l = 0;l+x<=n;l++){
33+
if(is_paliondrom(s.substr(l,x))){
34+
return l;
35+
}
36+
}
37+
return -1;
38+
}
39+
40+
string longestPalindrome(string s){
41+
int best_len = 0;
42+
string best_s = "";
43+
int n = s.length();
44+
for(int parity: {0,1}){
45+
int low = 1,high = n;
46+
if(low%2!=parity) low++;
47+
if(high%2!=parity) high--;
48+
cout<<low<<" "<<high<<" "<<parity<<endl;
49+
while(low <= high){
50+
int mid = (low + high)/2;
51+
if(mid%2 != parity){
52+
mid ++;
53+
}
54+
if(mid>high){
55+
break;
56+
}
57+
cout<<mid<<endl;
58+
int tmp = good(mid,s);
59+
if(tmp != -1){
60+
if(mid>best_len){
61+
best_len = mid;
62+
best_s = s.substr(tmp,mid);
63+
}
64+
low = mid + 2;
65+
}else {
66+
high = mid - 2;
67+
}
68+
}
69+
}
70+
return best_s;
71+
}
72+
73+
int solve()
74+
{
75+
//happy coding
76+
77+
string s;
78+
cin>>s;
79+
80+
string x = longestPalindrome(s);
81+
82+
cout<<x<<endl;
83+
84+
return 0;
85+
}
86+
int main(){
87+
int test = 1;
88+
scanf("%d", &test);
89+
while (test--)solve();return 0;
90+
}

0 commit comments

Comments
 (0)