最长回文字符串

给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。

示例 1:

输入: "babad"
输出: "bab"
注意: "aba" 也是一个有效答案。
示例 2:

输入: "cbbd"
输出: "bb"

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-palindromic-substring
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

// 解题思路:s[j][i] = (s[j] == s[i]) + s[j + 1][i - 1]
// 并且当j - i < 3时,(j - 1 - (i + 1)) + 1 < 2时,一定是为正确的
func longestPalindrome(s string) string { length := len(s) if length <= 1 { return s } dp := make([][]bool, length) start := 0 maxlen := 1 // 动态规划解法 for i := 0; i < length; i++ { dp[i] = make([]bool, length) dp[i][i] = true } for i := 1; i < length; i++ { for j := 0; j < i; j++ { if (s[j] == s[i]) {
          // 注意理解这个
if (i - j < 3) { dp[j][i] = true } else { dp[j][i] = dp[j+1][i-1] } } else { dp[j][i] = false } if (dp[j][i]) { tempLen := i - j + 1; if (maxlen < tempLen) { start = j maxlen = tempLen } } } } return s[start:start+maxlen] }

 

posted @ 2020-05-09 00:13  泥土里的绽放  阅读(192)  评论(0编辑  收藏  举报