我的代码适用于计算LCS的长度,但我在以下链接上应用相同的代码读取LCS,
http://en.wikipedia.org/wiki/Longest_common_subsequence_problem
但缺少一些字符串。你能告诉我我错过了什么吗?
Google Playground链接:http://play.golang.org/p/qnIWQqzAf5
func Back(table [][]int, str1, str2 string, i, j int) string {
if i == 0 || j == 0 {
return ""
} else if str1[i] == str2[j] {
return Back(table, str1, str2, i-1, j-1) + string(str1[i])
} else {
if table[i][j-1] > table[i-1][j] {
return Back(table, str1, str2, i, j-1)
} else {
return Back(table, str1, str2, i-1, j)
}
}
}
提前致谢。
答案 0 :(得分:2)
我认为问题出在你的索引中。如果要从0
- len-1
索引字符串,则表格应包含行数和列数,1大于字符串长度。在计算LCS的长度时,您似乎已经考虑到了这一点,但是当您返回LCS时却没有。您的i
和j
正确表示字符串的索引,但不能正确表示表格,该表格应大于i/j
的1。因此,检查0的基本条件是错误的,因为str1[0]
和str2[0]
是有效字符
所以你的代码应该是这样的:
func Back(table [][]int, str1, str2 string, i, j int) string {
if i == -1 || j == -1 {
return ""
} else if str1[i] == str2[j] {
return Back(table, str1, str2, i-1, j-1) + string(str1[i])
} else {
if table[i+1][j] > table[i][j+1] {
return Back(table, str1, str2, i, j-1)
} else {
return Back(table, str1, str2, i-1, j)
}
}
}