5-longestPalidrome

code

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
class Solution {
public:
string longestPalindrome(string s) {
int n = s.size(),l = 0,r = 0,length = 1,index = 0,max_length = 0;
for (int i = 0;i < n;i++) {
l = i - 1;
r = i + 1;
while (l >= 0 && s[l] == s[i]) {
length++;
l--;
}
while (r < n && s[r] == s[i]) {
length++;
r++;
}
while (l >= 0 && r < n && s[l] == s[r]) {
length += 2;
l--;
r++;
}
if (length > max_length) {
max_length = length;
index = l;
}
length = 1;
}
return s.substr(index + 1,max_length);
}
};


5-longestPalidrome
https://williammarioalan.github.io/2025/01/29/5-longestPalidrome/
Author
mario
Posted on
January 29, 2025
Licensed under