最长公共子串 二维数组 Go实现
作者:互联网
参考:https://blog.csdn.net/dongyanwen6036/article/details/87914940
//CommonSubstr 寻找两个字符串间的最大相同子串
func CommonSubstr(A string, B string) string {
//构造BxA的二维数组C,每个元素C[i][j]包含两个信息:1、该元素对应的B[i]与A[j]两个字符是否相同
//2、 如果B[i]与A[j]相同,且各倒退一个字符B[i-1]A[j-1]也相同,则与前面字符构成一个公共子串,
//在C[i][j]元素额外存储当前公共子串的长度1+C[i-1][j-1]的子串长度;如果B[i-1]A[j-1]不同
//则C[i][j]元素的公共子串的长度就只有当前公共字符一个
var irecord, nMax int
nMax = 0
var Common [][][]int
Common = make([][][]int, len(B), len(B))
for i := 0; i < len(B); i++ {
Common[i] = make([][]int, len(A), len(A))
for j := 0; j < len(A); j++ {
//Go初始化使用类型的零值,不用手动初始化
Common[i][j] = make([]int, 2, 2)
Common[i][j] = []int{0, 0}
if B[i] == A[j] {
Common[i][j][0] = 1
if i > 0 && j > 0 {
Common[i][j][1] = 1 + Common[i-1][j-1][1]
} else {
Common[i][j][1] = 1
}
if Common[i][j][1] > nMax {
nMax = Common[i][j][1]
irecord = i
}
} else {
Common[i][j][0] = 0
Common[i][j][1] = 0
}
}
}
if nMax == 0 {
return ""
} else {
return B[irecord-nMax+1 : irecord+1]
}
//
}
标签:子串,nMax,int,len,二维,Common,Go,irecord 来源: https://blog.csdn.net/HayPinF/article/details/112060556