Longest common substring

From Rosetta Code
Revision as of 11:18, 18 February 2015 by rosettacode>Geoffhacker (New draft task: longest common substring.)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Longest common substring is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

Write a program that prompts the user to enter two different strings, and then output their longest common substring.

C#

<lang csharp>using System;

namespace LongestCommonSubstring {

   class Program
   {
       static void Main(string[] args)
       {
           Console.Write("Enter word 1: ");
           string word1 = Console.ReadLine();
           Console.Write("Enter word 2: ");
           string word2 = Console.ReadLine();
           Console.WriteLine(lcs(word1, word2));
           Console.ReadKey(true);
       }
       public static string lcs(string a, string b)
       {
           int[,] lengths = new int[a.Length, b.Length];
           int greatestLength = 0;
           string output = "";
           //For each character in string a...
           for (int i = 0; i < a.Length; i++)
           {
               //For each character in string b...
               for (int j = 0; j < b.Length; j++)
               {
                   //Keep a running count of the number of consecutive characters in each that are the same.
                   if (a[i] == b[j])
                   {
                       if (i == 0 || j == 0)
                       {
                           lengths[i, j] = 1;
                       }
                       else
                       {
                           lengths[i, j] = lengths[i - 1, j - 1] + 1;
                       }
                       //When you find the greatest count so far, note the substring of which it is. 
                       if (lengths[i, j] > greatestLength)
                       {
                           greatestLength = lengths[i, j];
                           output = a.Substring(i - greatestLength + 1, greatestLength);
                       }
                   }
                   else
                   {
                       lengths[i, j] = 0;
                   }
               }
           }
           //Output the substring you've noted.
           return output;
       }
   }

}</lang>