// C# program to find the minimum of insertion and deletion
// using memoization.
using System;
class GfG {
static int lcs(string s1, string s2, int m, int n,
int[, ] memo) {
// Base case: If either string is empty, the LCS
// length is 0
if (m == 0 || n == 0) {
return 0;
}
// If the value is already computed, return it from
// the memo array
if (memo[m, n] != -1) {
return memo[m, n];
}
// If the last characters of both substrings match
if (s1[m - 1] == s2[n - 1]) {
// Include the matching character in LCS and
// recurse for remaining substrings
memo[m, n]
= 1 + lcs(s1, s2, m - 1, n - 1, memo);
}
else {
// If the last characters do not match, find the
// maximum LCS length by:
// 1. Excluding the last character of s1
// 2. Excluding the last character of s2
memo[m, n]
= Math.Max(lcs(s1, s2, m, n - 1, memo),
lcs(s1, s2, m - 1, n, memo));
}
// Return the computed value
return memo[m, n];
}
static int minOperations(string s1, string s2) {
int m = s1.Length;
int n = s2.Length;
// Initialize the memoization array with -1
// (indicating uncalculated values)
int[, ] memo = new int[m + 1, n + 1];
for (int i = 0; i <= m; i++) {
for (int j = 0; j <= n; j++) {
memo[i, j] = -1;
}
}
// Calculate the length of LCS for s1[0..m-1] and
// s2[0..n-1]
int lengthLcs = lcs(s1, s2, m, n, memo);
// Characters to delete from s1
int minDeletions = m - lengthLcs;
// Characters to insert into s1
int minInsertions = n - lengthLcs;
// Total operations needed
return minDeletions + minInsertions;
}
static void Main(string[] args) {
string s1 = "AGGTAB";
string s2 = "GXTXAYB";
int res = minOperations(s1, s2);
Console.WriteLine(res);
}
}