Skip to content

Instantly share code, notes, and snippets.

@riyadparvez
Created July 4, 2013 04:06
Show Gist options
  • Save riyadparvez/5924851 to your computer and use it in GitHub Desktop.
Save riyadparvez/5924851 to your computer and use it in GitHub Desktop.
Length of longest common subsequence in C#
private static int Max(int int1, int int2)
{
return int1 > int2 ? int1 : int2;
}
public static int LongestCommonSubsequence(string str1, string str2)
{
int [,] arr = new int [str1.Length+1, str2.Length+1];
for(int i=0; i<=str2.Length; i++)
{
arr[0, i] = 0;
}
for (int i = 0; i <= str1.Length; i++)
{
arr[i, 0] = 0;
}
for (int i = 1; i <= str1.Length; i++)
{
for (int j = 1; j <= str2.Length; j++)
{
if (str1[i-1] == str2[j-1])
{
arr[i, j] = arr[i - 1, j - 1] + 1;
}
else
{
arr[i, j] = Max(arr[i-1, j], arr[i, j-1]);
}
}
}
return arr[str1.Length, str2.Length];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment