-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestPalindromicSubstring.cpp
More file actions
60 lines (51 loc) · 1.66 KB
/
LongestPalindromicSubstring.cpp
File metadata and controls
60 lines (51 loc) · 1.66 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
#https://leetcode.com/submissions/detail/104038255/
#Intuition: for each doPal(), we place two pointers side by side and compare the substrings, then move the right pointer one step
#right and compare with the left pointer, then move the left pointer one step one step left and compare with the right pointer. --repeat.
#Note flags.
class Solution {
private:
int low,high,maxlen = 0;
public:
string longestPalindrome(string s) {
int len = s.length();
if (len < 2){return s;}
int roll = len -1;
maxlen = 0;
while(roll >= 0){
doPal(s,roll,len-1);
--roll;
}
return s.substr(low, high-low +1);
}
void doPal(string s, int i, int indx){
int l = i - 1 ;
int r = i ;
int sm = 0; int bg = 0;
bool flagA = false;bool flagB = false;
while(l >= 0 && r <= indx ){
if ((s[l] == s[r] && flagA) || (r-l <= 1 && s[l] == s[r]) ){
sm = l;
bg = r;
flagA = true;
} else{
flagA = false;
}
++r;
if((r<=indx && s[l] == s[r] && flagB) || (r-l <= 2 && s[l] == s[r]) ){
sm = l;
bg= r;
flagB = true;
} else{
flagB = false;
}
--l;
if ( !flagA && !flagB ){
break;
}
}
if (bg - sm > maxlen){
maxlen = bg - sm ;
low = sm; high = bg;
}
}
};