LCS Dynamic Programming Table (Go)

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

GoData Integrity

Code

gosnippet
18 lines
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)
}

How it works

Count the function longestCommonSubseq as the entire surface area of LCS Dynamic Programming Table (Go).

Iteration happens inside for i := range dp { dp[i] = make([]int, n+1) } — everything outside it runs once.

Applying it

Entry signature: func longestCommonSubseq(a, b string) string

Statements that matter

for i := range dp { dp[i] = make([]int, n+1) }
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-- }
result := make([]byte, 0, dp[m][n])

Interactive Tools for This Topic

FAQ

Does the runtime need any help from npm, pip, cargo, or the like?
No — the package manager has nothing to do here; nothing is declared. The file defines `longestCommonSubseq` at load time.