-
Notifications
You must be signed in to change notification settings - Fork 0
/
Longest_palindromic_substring(GFG)(very imp).cpp
65 lines (49 loc) · 1.45 KB
/
Longest_palindromic_substring(GFG)(very imp).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
63
64
65
//{ Driver Code Starts
//Initial template for C++
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
//User function template for C++
class Solution{
public:
string longestPalindrome(string s){
string str="";
int n=s.length();
//iterate over the string
for(int i=0;i<n;i++){
//initialize two pointer
int left=i, right=i;
// expand the range of palindrome,
// while two pointers are same
while(left>=0 && s[left]==s[i])left--;
while(right<n && s[right]==s[i])right++;
// expand the range of palindrome,
// while two pointers are same
while(left>=0 && right<n && s[left]==s[right]){
left--;
right++;
}
// get the substring that is palindrome
string candidate = s.substr(left+1, right-left-1);
// now check,
// if current palindrome is longer than the previous one
if(candidate.length()>str.length()){
str=candidate;
}
}
return str;
}
};
//{ Driver Code Starts.
int main(){
int t;
cin>>t;
while(t--){
string S;
cin>>S;
Solution ob;
cout<<ob.longestPalindrome(S)<<endl;
}
return 0;
}
// } Driver Code Ends