I want a program to return the longest common sub-string of two strings.
ex:- if two strings are
string str1="Hello how are you"
string str2="Hello chinni, how you doing"
the output should return 'Hello'(The longest common substring)
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Karthikeyan KPosted Aug 26, 2015, 2:16 AM
namespace LongestCommonSubstring
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(lcs("Hello how are you", "Hello chinni, how you doing"));
Console.ReadKey(true);
}
public static string lcs(string a, string b)
{
var lengths = new int[a.Length, b.Length];
int greatestLength = 0;
string output = "";
for (int i = 0; i < a.Length; i++)
{
for (int j = 0; j < b.Length; j++)
{
if (a[i] == b[j])
{
lengths[i, j] = i == 0 || j == 0 ? 1 : lengths[i - 1, j - 1] + 1;
if (lengths[i, j] > greatestLength)
{
greatestLength = lengths[i, j];
output = a.Substring(i - greatestLength + 1, greatestLength);
}
}
else
{
lengths[i, j] = 0;
}
}
}
return output;
}
}
}