LCS Dynamic Programming Table (Go)

Compute the longest common subsequence of two Go strings using dynamic programming with table reconstruction.

GoData Integrity

Code

snippet
package main

func longestCommonSubseq(a, b string) string {
	m, n := len(a), len(b)
	dp := make([][]int, m+1)
	for i := range dp { dp[i] = make([]int, n+1) }
	for i := 1; i <= m; i++ {
		for j := 1; j <= n; j++ {
			if a[i-1] == b[j-1] { dp[i][j] = dp[i-1][j-1] + 1 } else if dp[i-1][j] > dp[i][j-1] { dp[i][j] = dp[i-1][j] } else { dp[i][j] = dp[i][j-1] }
		}
	}
	result := make([]byte, 0, dp[m][n])
	i, j := m, n
	for i > 0 && j > 0 {
		if a[i-1] == b[j-1] { result = append([]byte{a[i-1]}, result...); i--; j-- } else if dp[i-1][j] > dp[i][j-1] { i-- } else { j-- }
	}
	return string(result)
}