-
Notifications
You must be signed in to change notification settings - Fork 231
Expand file tree
/
Copy pathLongest_Palindromic_Substring_Problem.cpp
More file actions
45 lines (38 loc) · 1.11 KB
/
Longest_Palindromic_Substring_Problem.cpp
File metadata and controls
45 lines (38 loc) · 1.11 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
#Longest_Palindromic_Substring_Problem
class Solution {
public:
string longestPalindrome(string s) {
int n=s.size();
if(n==0)return "";
int i=0;
int maxi=0;
string ans="";
int lef,rig;
while(i<n){
//odd case
lef=i; rig=i;
while(lef>=0&&rig<=n-1&&s[lef]==s[rig]){
if(maxi<rig-lef+1){
string t(s.begin()+lef,s.begin()+rig+1);
ans=t;
maxi=rig-lef+1;
}
lef--;
rig++;
}
//even case
lef=i;rig=i+1;
while(lef>=0&&rig<=n-1&&s[lef]==s[rig]){
if(maxi<rig-lef+1){
string t(s.begin()+lef,s.begin()+rig+1);
ans=t;
maxi=rig-lef+1;
}
lef--;
rig++;
}
i++;
}
return ans;
}
};