算法:动态规划
1.简介
将一个大的问题问题拆成小的问题,先解决小的问题从而解决大的问题。
2.示例
以查找"vista"
与"hish"
中最长相同子串为例。
以"vista"
与"hish"
建立一个表,按字符依次比较。如果不相同设置相同字符数为0,如果相同获取两边上一个字母(x-i,y-1)累计相同字符数,将其+1保存到当前位置。遍历整张表,计录累计相同字符数最大的位置,这样就能取得长相同子串。
v | i | s | t | a | |
---|---|---|---|---|---|
h | 0 | 0 | 0 | 0 | 0 |
i | 0 | 1 | 0 | 0 | 0 |
s | 0 | 0 | 2 | 0 | 0 |
h | 0 | 0 | 0 | 0 | 0 |
3.演示
package main
import "fmt"
func main() {
fmt.Println(substring("vista", "hish"))
fmt.Println(substring("fish", "hish"))
}
func createMatrix(rows, cols int) [][]int {
cell := make([][]int, rows)
for i := range cell {
cell[i] = make([]int, cols)
}
return cell
}
// 相同子串
func substring(a, b string) string {
lcs := 0
lastSubIndex := 0
cell := createMatrix(len(a)+1, len(b)+1)
for i := 1; i <= len(a); i++ {
for j := 1; j <= len(b); j++ {
if a[i-1] == b[j-1] {
cell[i][j] = cell[i-1][j-1] + 1
if cell[i][j] > lcs {
lcs = cell[i][j]
lastSubIndex = i
}
} else {
cell[i][j] = 0
}
}
}
return a[lastSubIndex-lcs : lastSubIndex]
}
4.参考
- 《图解算法》