Complete the code to initialize the maximum length of palindrome found so far.
int maxLength = [1];We start with maxLength = 0 because initially no palindrome substring is found.
Complete the code to expand around the center and return the length of palindrome.
while (left >= 0 && right < s.size() && s[left] == s[right]) { left--; right++; } return right - left - [1];
We subtract 1 because after the loop exits, 'right' points one past the end and 'left' points one before the start of the palindrome, so right - left - 1 gives the correct length.
Fix the error in the code to update the start index when a longer palindrome is found.
if (len > maxLength) { maxLength = len; start = i - [1] / 2; }
We subtract 1 from len before dividing by 2 to correctly find the start index for even length palindromes.
Fill both blanks to correctly call the expand function for odd and even length palindromes.
int len1 = expandAroundCenter(s, i, i); int len2 = expandAroundCenter(s, i, [1]); int len = std::max(len1, [2]);
For even length palindrome, we expand around centers i and i+1. Then take max of len1 and len2.
Fill all three blanks to complete the function that finds the longest palindromic substring.
std::string longestPalindrome(std::string s) {
int start = 0, maxLength = 1;
for (int i = 0; i < s.size(); i++) {
int len1 = expandAroundCenter(s, i, i);
int len2 = expandAroundCenter(s, i, i + 1);
int len = std::max(len1, len2);
if (len > maxLength) {
maxLength = len;
start = i - [1] / 2;
}
}
return s.substr(start, [2]);
}
int expandAroundCenter(const std::string& s, int left, int right) {
while (left >= 0 && right < s.size() && s[left] == s[right]) {
left--;
right++;
}
return right - left - [3];
}Start index is adjusted by (len - 1)/2. The substring length is maxLength. The expand function subtracts 1 after expansion.
