-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestPalindromeString.cpp
More file actions
69 lines (56 loc) · 1.39 KB
/
LongestPalindromeString.cpp
File metadata and controls
69 lines (56 loc) · 1.39 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
58
59
60
61
62
63
64
65
66
67
68
69
//{ Driver Code Starts
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution {
public:
string longestPalin (string S) {
string ans="";
int n=S.size();
int maxl=0;
int l=0;
int r=0;
for(int i=0; i<n; i++){
//if longest substring palindrome is of odd lemgth
int left=i;
int right=i;
while(left>=0&&right<=(n-1)&&S[left]==S[right]){
left--;
right++;
}
if(right-left+1>maxl){
maxl=right-left+1;
l=left+1;
r=right-1;
}
//if longest substring palindrome is of even lemgth
left=i;
right=i+1;
while(left>=0&&right<=n-1&&S[left]==S[right]){
left--;
right++;
}
if(right-left+1>2&&right-left+1>maxl){
maxl=right-left+1;
l=left+1;
r=right-1;
}
}
for(int i=l; i<=r; i++){
ans=ans+S[i];
}
return ans;
}
};
//{ Driver Code Starts.
int main()
{
int t; cin >> t;
while (t--)
{
string S; cin >> S;
Solution ob;
cout << ob.longestPalin (S) << endl;
}
}
// } Driver Code Ends