longestCommonSubsequence function

int longestCommonSubsequence(
  1. String a,
  2. String b
)

🔗 Longest Common Subsequence (LCS) - Dynamic Programming

Returns the length of the longest common subsequence between a and b.

Time Complexity: O(m * n) Space Complexity: O(m * n)

Implementation

int longestCommonSubsequence(String a, String b) {
  final m = a.length, n = b.length;
  final dp = List.generate(m + 1, (_) => List<int>.filled(n + 1, 0));
  for (int i = 1; i <= m; i++) {
    for (int j = 1; j <= n; j++) {
      if (a[i - 1] == b[j - 1]) {
        dp[i][j] = dp[i - 1][j - 1] + 1;
      } else {
        dp[i][j] = dp[i - 1][j] > dp[i][j - 1] ? dp[i - 1][j] : dp[i][j - 1];
      }
    }
  }
  return dp[m][n];
}