Intermediate Level
Implement the longestPalindromicSubstringLength method that returns the length of the longest palindromic substring.
The input contains a string text. Your task is to return the length of the longest palindromic substring.
A substring must be continuous, and it is a palindrome if it reads the same forward and backward. For example, in babad, a longest palindromic substring has length 3.
Example 1
Input
text (string) =
babadReturns (int)
3Example 2
Input
text (string) =
cbbdReturns (int)
2Example 3
Input
text (string) =
aReturns (int)
1Every palindrome expands around a center. The center can be one character for odd-length palindromes or two characters for even-length palindromes.
For each index, expand around both possible centers while the left and right characters are equal. Track the largest length found.
This checks all possible palindromic substrings without generating every substring separately.
Pseudocode:
function longestPalindromicSubstringLength(text):
best = 0
for center from 0 to length(text) - 1:
oddLength = expandAroundCenter(text, center, center)
evenLength = expandAroundCenter(text, center, center + 1)
best = max(best, oddLength, evenLength)
return best
function expandAroundCenter(text, left, right):
while left >= 0 and right < length(text) and text[left] == text[right]:
left--
right++
return right - left - 1Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run