Skip to content

Commit 24eb5df

Browse files
committed
add logest-palindromic-subsequence
1 parent 860eb21 commit 24eb5df

File tree

2 files changed

+80
-0
lines changed

2 files changed

+80
-0
lines changed

go/longest-palindromic-subsequence.go

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package leetcode
2+
3+
// https://leetcode.com/problems/longest-palindromic-subsequence/
4+
5+
func longestPalindromeSubseq(s string) int {
6+
length := len(s)
7+
if length == 0 {
8+
return 0
9+
}
10+
dp := make([][]int, length)
11+
for i := 0; i < length; i++ {
12+
dp[i] = make([]int, length)
13+
}
14+
15+
for i := 0; i < length; i++ {
16+
for j := 0; j < length-i; j++ {
17+
k := i + j
18+
dp[j][k] = 1
19+
if j == k {
20+
continue
21+
}
22+
if i == 1 && s[j] == s[k] {
23+
dp[j][j+1] = 2
24+
continue
25+
}
26+
max := dp[j][k-1]
27+
if max < dp[j+1][k] {
28+
max = dp[j+1][k]
29+
}
30+
if s[j] == s[k] {
31+
max = dp[j+1][k-1] + 2
32+
}
33+
dp[j][k] = max
34+
}
35+
}
36+
// for _, item := range dp {
37+
// fmt.Println(item)
38+
// }
39+
return dp[0][length-1]
40+
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package leetcode
2+
3+
import "testing"
4+
5+
func TestLongestPalindromeSubseq(t *testing.T) {
6+
tests := []struct {
7+
input string
8+
expect int
9+
}{
10+
{
11+
input: "bbbab",
12+
expect: 4,
13+
}, {
14+
input: "cbbd",
15+
expect: 2,
16+
}, {
17+
input: "abcabcba",
18+
expect: 7,
19+
}, {
20+
input: "",
21+
expect: 0,
22+
}, {
23+
input: "a",
24+
expect: 1,
25+
}, {
26+
input: "aa",
27+
expect: 2,
28+
}, {
29+
input: "euazbipzncptldueeuechubrcourfpftcebikrxhybkymimgvldiwqvkszfycvqyvtiwfckexmowcxztkfyzqovbtmzpxojfofbvwnncajvrvdbvjhcrameamcfmcoxryjukhpljwszknhiypvyskmsujkuggpztltpgoczafmfelahqwjbhxtjmebnymdyxoeodqmvkxittxjnlltmoobsgzdfhismogqfpfhvqnxeuosjqqalvwhsidgiavcatjjgeztrjuoixxxoznklcxolgpuktirmduxdywwlbikaqkqajzbsjvdgjcnbtfksqhquiwnwflkldgdrqrnwmshdpykicozfowmumzeuznolmgjlltypyufpzjpuvucmesnnrwppheizkapovoloneaxpfinaontwtdqsdvzmqlgkdxlbeguackbdkftzbnynmcejtwudocemcfnuzbttcoew",
30+
expect: 159,
31+
},
32+
}
33+
34+
for _, item := range tests {
35+
actual := longestPalindromeSubseq(item.input)
36+
if actual != item.expect {
37+
t.Fatalf("%s expect %d, actual %d\n", item.input, item.expect, actual)
38+
}
39+
}
40+
}

0 commit comments

Comments
 (0)