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) = babad
Returns (int) 3

Example 2

Input
text (string) = cbbd
Returns (int) 2

Example 3

Input
text (string) = a
Returns (int) 1

Every 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 - 1
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.