5. Longest Palindromic Substring
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.Example 2:
Input: "cbbd"
Output: "bb"// Expand from the center
string longestPalindrome(string s) { // time: O(n^2); space: O(1)
int n = s.size(), start = 0, max_len = 0;
if (n < 2) return s;
for (int i = 0; i < n; ++i) {
helper(s, i, i, start, max_len); // odd length
helper(s, i, i + 1, start, max_len); // even length
}
return s.substr(start, max_len);
}
void helper(string& s, int l, int r, int& start, int& max_len) {
while (l >= 0 && r < s.size() && s[l] == s[r]) {
--l, ++r;
}
if (max_len < r - l - 1) {
max_len = r - l - 1;
start = l + 1;
}
return;
}Last updated
Was this helpful?