mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
0005.最长回文子串增加go的dp解法
0005.最长回文子串增加go的dp解法
This commit is contained in:
@ -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]
|
||||
}
|
||||
|
||||
|
||||
```
|
||||
|
||||
|
Reference in New Issue
Block a user