题解 | #最长回文子串#

最长回文子串

https://www.nowcoder.com/practice/b4525d1d84934cf280439aeecc36f4af

package main

func getLongestPalindrome( A string ) int {
    // dp[i][j] 代表以 i 起始和 j 结尾的子串中是否是回文子串
    // dp[i][j] = (A[i] == A[j]) 时 dp[i+1][j-1] 左下方
    n, ans := len(A), 1
    dp := make([][]bool, n)
    for i := range dp {
        dp[i] = make([]bool, n)
        dp[i][i] = true
    }
    for j := 1; j < n; j++ {
        for i := 0; i < j; i++ {
            if A[i] == A[j] && (j-i+1 <= 3 || dp[i+1][j-1]) {
                dp[i][j] = true
                ans = max(ans, j-i+1)
            }
        }
    }
    return ans
}   

func max(a, b int) int { if a < b { return b }; return a }

全部评论

相关推荐

07-02 13:52
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务