Leetcode 5. Longest Palindromic Substring (Medium) (cpp)
Tag: String
Difficulty: Medium
/*
5. Longest Palindromic Substring (Medium)
Given a string S, find the longest palindromic substring in S. You may assume that the maximum
length of S is 1000, and there exists one unique longest palindromic substring.
*/
class Solution {
public:
string longestPalindrome(string s) {
string res;
int _size = s.length(), l_max = 0, len_max = 0, l, r;
for (int i = 0; i < _size && _size - i > len_max / 2;) {
l = r = i;
while (r < _size - 1 && s[r] == s[r + 1]) {
r++;
}
i = r + 1;
while (l > 0 && r < _size - 1 && s[l - 1] == s[r + 1]) {
l--;
r++;
}
if (r - l + 1 > len_max) {
len_max = r - l + 1;
l_max = l;
}
}
return s.substr(l_max, len_max);
}
};