LeetCode in TypeScript

5. Longest Palindromic Substring

Medium

Given a string s, return the longest palindromic substring in s.

Example 1:

Input: s = “babad”

Output: “bab”

Explanation: “aba” is also a valid answer.

Example 2:

Input: s = “cbbd”

Output: “bb”

Constraints:

Solution

function longestPalindrome(s: string): string {
    const newStr: string[] = new Array(s.length * 2 + 1)
    newStr[0] = '#'
    for (let i = 0; i < s.length; i++) {
        newStr[2 * i + 1] = s.charAt(i)
        newStr[2 * i + 2] = '#'
    }
    const dp: number[] = new Array(newStr.length)
    let friendCenter: number = 0
    let friendRadius: number = 0
    let lpsCenter: number = 0
    let lpsRadius: number = 0
    for (let i = 0; i < newStr.length; i++) {
        dp[i] =
            friendCenter + friendRadius > i ? Math.min(dp[2 * friendCenter - i], friendCenter + friendRadius - i) : 1
        while (i + dp[i] < newStr.length && i - dp[i] >= 0 && newStr[i + dp[i]] === newStr[i - dp[i]]) {
            dp[i]++
        }
        if (friendCenter + friendRadius < i + dp[i]) {
            friendCenter = i
            friendRadius = dp[i]
        }
        if (lpsRadius < dp[i]) {
            lpsCenter = i
            lpsRadius = dp[i]
        }
    }
    return s.substring((lpsCenter - lpsRadius + 1) / 2, (lpsCenter + lpsRadius - 1) / 2)
}

export { longestPalindrome }