[Golang] Longest Common Subsequence Length via Recursion


Compute the length of longest common subsequence via recursion in Go.

Run Code on Go Playground

LCS Length via Recursion in Go:

package lcs

func max(a, b int) int {
      if a > b {
              return a
      }
      return b
}

func LCSLength(x, y []byte) int {
      if len(x) == 0 || len(y) == 0 {
              return 0
      }

      if x[len(x)-1] == y[len(y)-1] {
              return 1 + LCSLength(x[0:len(x)-1], y[0:len(y)-1])
      } else {
              return max(LCSLength(x, y[0:len(y)-1]), LCSLength(x[0:len(x)-1], y))
      }
}

Testing:

package lcs

import (
      "testing"
)

func TestLCSLength(t *testing.T) {
      if LCSLength([]byte(`ABCDGH`), []byte(`AEDFHR`)) != 3 {
              t.Error("should be 3")
      }
      if LCSLength([]byte(`AGGTAB`), []byte(`GXTXAYB`)) != 4 {
              t.Error("should be 4")
      }
}

Tested on:


References:

[1]Dynamic Programming | Set 4 (Longest Common Subsequence) - GeeksforGeeks