mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
Merge pull request #1336 from Hanmengnan/master
更新0516.最长回文子序列的Go实现提供了一种更优的方法
This commit is contained in:
@ -186,29 +186,28 @@ class Solution:
|
||||
Go:
|
||||
```Go
|
||||
func longestPalindromeSubseq(s string) int {
|
||||
lenth:=len(s)
|
||||
dp:=make([][]int,lenth)
|
||||
for i:=0;i<lenth;i++{
|
||||
for j:=0;j<lenth;j++{
|
||||
if dp[i]==nil{
|
||||
dp[i]=make([]int,lenth)
|
||||
}
|
||||
if i==j{
|
||||
dp[i][j]=1
|
||||
size := len(s)
|
||||
max := func(a, b int) int {
|
||||
if a > b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
dp := make([][]int, size)
|
||||
for i := 0; i < size; i++ {
|
||||
dp[i] = make([]int, size)
|
||||
dp[i][i] = 1
|
||||
}
|
||||
for i := size - 1; i >= 0; i-- {
|
||||
for j := i + 1; j < size; j++ {
|
||||
if s[i] == s[j] {
|
||||
dp[i][j] = dp[i+1][j-1] + 2
|
||||
} else {
|
||||
dp[i][j] = max(dp[i][j-1], dp[i+1][j])
|
||||
}
|
||||
}
|
||||
}
|
||||
for i:=lenth-1;i>=0;i--{
|
||||
for j:=i+1;j<lenth;j++{
|
||||
if s[i]==s[j]{
|
||||
dp[i][j]=dp[i+1][j-1]+2
|
||||
}else {
|
||||
dp[i][j]=max(dp[i+1][j],dp[i][j-1])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return dp[0][lenth-1]
|
||||
return dp[0][size-1]
|
||||
}
|
||||
```
|
||||
|
||||
|
Reference in New Issue
Block a user