最长公共子序列

给定两个字符串str1和str2,输出两个字符串的最长公共子序列。如果最长公共子序列为空,则返回"-1"。目前给出的数据,仅仅会存在一个最长的公共子序列

输入

"1A2C3D4B56","B1D23A456A"

返回值

"123456"

参考 https://blog.csdn.net/hrn1216/article/details/51534607


Golang实现
func LCS2( str1 string ,  str2 string ) string {

	row := len(str1)
	col := len(str2)
	if row == 0 || col == 0 {
		return ""
	}

	dp := make([][]int, row+1)
	for i:=0;i<row+1;i++{
		dp[i] = make([]int, col+1)
	}
	for i:=0;i<row+1;i++ {
		dp[i][0] = 0
	}
	for i:=0;i<col+1;i++ {
		dp[0][i] = 0
	}
	
	for i:=1;i<=row;i++{
		for j:=1;j<=col;j++{
			if str1[i-1] == str2[j-1] {
				dp[i][j] = dp[i-1][j-1]+1
			}else {
				if dp[i][j-1] > dp[i-1][j] {
					dp[i][j] = dp[i][j-1]
				}else{
					dp[i][j] = GetMaxInt(dp[i][j-1] , dp[i-1][j])
				}
			}
		}
	}

	//因为当前dp[i][j]可以由三种方式得到,分别是 dp[i-1][j-1]+1 ;dp[i][j-1] ; dp[i-1][j]
	//并且只有第一种方式才表明当前的 str1[i-1] == str2[j-1]
	res := ""
	for i, j:=row,col; i>0 && j > 0; {
		if str1[i-1] == str2[j-1] {
			res = string(str1[i-1]) + res
			i--; j--
		}else if dp[i][j-1] > dp[i-1][j] {
			j--
		}else{
			i--
		}
	}

	return  res
}

  

 

原文地址:https://www.cnblogs.com/jiguang321/p/14769368.html