0005-最长回文子串

给你一个字符串 s,找到 s 中最长的回文子串。

示例 1:

输入:s = "babad"
输出:"bab"
解释:"aba" 同样是符合题意的答案。
示例 2:

输入:s = "cbbd"
输出:"bb"
示例 3:

输入:s = "a"
输出:"a"
示例 4:

输入:s = "ac"
输出:"a"

提示:

1 <= s.length <= 1000
s 仅由数字和英文字母(大写和/或小写)组成

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-palindromic-substring

参考:

python

# 0005.最长回文串

class Solution:
    def longestPalindrome(self,s: str) -> str:
        """
        动态规划,647基础上更改
        :param s:
        :return:
        """
        dp = [[False] * len(s) for _ in range(len(s))]
        Max = -1
        indexs = (0, 0)
        for i in range(len(s) - 1, -1, -1):
            for j in range(i, len(s)):
                if s[i] == s[j] and (j-i <= 1 or dp[i+1][j-1]):
                    dp[i][j] = True
                    if j-i > Max:
                        Max = j-i
                        indexs = (i, j)

        return s[indexs[0]:indexs[1]+1]

golang

package dynamicPrograming

// 动态规划, 647基础上修改
func longestPalindromic(s string) string {
	dp := make([][]bool, len(s))
	for i := range dp {
		dp[i] = make([]bool, len(s))
	}
	var MAX int = -1
	indexs := make([]int, 2)
	for i:=len(s)-1;i>=0;i-- {
		for j:=i;j<len(s);j++ {
			if s[i] == s[j] && (j-i <= 1 || dp[i+1][j-1] == true) {
				dp[i][j] = true
				if j-i > MAX {
					MAX = j-i
					indexs[0], indexs[1] = i, j
				}
			}
		}
	}
	return s[indexs[0]:indexs[1]+1]
}

上一篇:2021-08-18


下一篇:小程序:左右滑动切换tab选项及页面