Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit be18cd3

Browse files
Merge pull request youngyangyang04#1336 from Hanmengnan/master
更新0516.最长回文子序列的Go实现提供了一种更优的方法
2 parents b2b3227 + 34b4ffa commit be18cd3

File tree

1 file changed

+17
-18
lines changed

1 file changed

+17
-18
lines changed

‎problems/0516.最长回文子序列.md‎

Lines changed: 17 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -186,29 +186,28 @@ class Solution:
186186
Go:
187187
```Go
188188
func longestPalindromeSubseq(s string) int {
189-
lenth:=len(s)
190-
dp:=make([][]int,lenth)
191-
for i:=0;i<lenth;i++{
192-
for j:=0;j<lenth;j++{
193-
if dp[i]==nil{
194-
dp[i]=make([]int,lenth)
195-
}
196-
if i==j{
197-
dp[i][j]=1
198-
}
189+
size := len(s)
190+
max := func(a, b int) int {
191+
if a > b {
192+
return a
199193
}
194+
return b
200195
}
201-
for i:=lenth-1;i>=0;i--{
202-
for j:=i+1;j<lenth;j++{
203-
if s[i]==s[j]{
204-
dp[i][j]=dp[i+1][j-1]+2
205-
}else {
206-
dp[i][j]=max(dp[i+1][j],dp[i][j-1])
196+
dp := make([][]int, size)
197+
for i := 0; i < size; i++ {
198+
dp[i] = make([]int, size)
199+
dp[i][i] = 1
200+
}
201+
for i := size - 1; i >= 0; i-- {
202+
for j := i + 1; j < size; j++ {
203+
if s[i] == s[j] {
204+
dp[i][j] = dp[i+1][j-1] + 2
205+
} else {
206+
dp[i][j] = max(dp[i][j-1], dp[i+1][j])
207207
}
208208
}
209209
}
210-
211-
return dp[0][lenth-1]
210+
return dp[0][size-1]
212211
}
213212
```
214213

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /