forked from TheAlgorithms/Go
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlongestpalindromicsubsequence.go
More file actions
51 lines (44 loc) · 907 Bytes
/
longestpalindromicsubsequence.go
File metadata and controls
51 lines (44 loc) · 907 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// longest palindromic subsequence
// http://www.geeksforgeeks.org/dynamic-programming-set-12-longest-palindromic-subsequence/
package dynamic
func lpsRec(word string, i, j int) int {
if i == j {
return 1
}
if i > j {
return 0
}
if word[i] == word[j] {
return 2 + lpsRec(word, i+1, j-1)
}
return Max(lpsRec(word, i, j-1), lpsRec(word, i+1, j))
}
// LpsRec function
func LpsRec(word string) int {
return lpsRec(word, 0, len(word)-1)
}
// LpsDp function
func LpsDp(word string) int {
N := len(word)
dp := make([][]int, N)
for i := 0; i < N; i++ {
dp[i] = make([]int, N)
dp[i][i] = 1
}
for l := 2; l <= N; l++ {
// for length l
for i := 0; i < N-l+1; i++ {
j := i + l - 1
if word[i] == word[j] {
if l == 2 {
dp[i][j] = 2
} else {
dp[i][j] = 2 + dp[i+1][j-1]
}
} else {
dp[i][j] = Max(dp[i+1][j], dp[i][j-1])
}
}
}
return dp[0][N-1]
}