From 41c480371c4a9c41f9e0a06d35810529b15c8c91 Mon Sep 17 00:00:00 2001 From: SwaggyP <1352164869@qq.com> Date: Wed, 24 Aug 2022 12:41:38 +0800 Subject: [PATCH] =?UTF-8?q?0005.=E6=9C=80=E9=95=BF=E5=9B=9E=E6=96=87?= =?UTF-8?q?=E5=AD=90=E4=B8=B2=E5=A2=9E=E5=8A=A0go=E7=9A=84dp=E8=A7=A3?= =?UTF-8?q?=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 0005.最长回文子串增加go的dp解法 --- problems/0005.最长回文子串.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/problems/0005.最长回文子串.md b/problems/0005.最长回文子串.md index d53acf63..6e407d6e 100644 --- a/problems/0005.最长回文子串.md +++ b/problems/0005.最长回文子串.md @@ -363,6 +363,34 @@ class Solution: Go: ```go +func longestPalindrome(s string) string { + maxLen := 0 + left := 0 + length := 0 + dp := make([][]bool, len(s)) + for i := 0; i < len(s); i++ { + dp[i] = make([]bool,len(s)) + } + for i := len(s)-1; i >= 0; i-- { + for j := i; j < len(s); j++ { + if s[i] == s[j]{ + if j-i <= 1{ // 情况一和情况二 + length = j-i + dp[i][j]=true + }else if dp[i+1][j-1]{ // 情况三 + length = j-i + dp[i][j] = true + } + } + } + if length > maxLen { + maxLen = length + left = i + } + } + return s[left: left+maxLen+1] +} + ```