Advertisement
Danielos168

Najdłuższy wspólny podciąg

Nov 20th, 2019
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.35 KB | None | 0 0
  1. namespace Zad3
  2. {
  3.     class Program
  4.     {
  5.        
  6.         static int[,] LongestCommonSubsequence(string s1, string s2)
  7.         {
  8.             int[,] common = new int[s1.Length + 1, s1.Length + 1];
  9.             for (int i = 1; i < s1.Length; i++)
  10.             {
  11.                 for (int j = 1; j < s2.Length; j++)
  12.                 {
  13.                     if (s1[i - 1] == s2[j - 1]) common[i, j] = common[i - 1, j - 1] + 1;
  14.                     else common[i, j] = common[i - 1, j] > common[i, j - 1] ? common[i - 1, j] : common[i, j - 1];
  15.                 }
  16.             }
  17.  
  18.             return common;
  19.         }
  20.         static string WriteLCS(int[,] c, string s1, string s2, int i, int j)
  21.         {
  22.             if (i == 0 || j == 0)
  23.                 return "";
  24.             else if (s1[i - 1] == s2[j - 1])
  25.                 return WriteLCS(c, s1, s2, i - 1, j - 1) + s1[i - 1];
  26.             else if (c[i, j - 1] > c[i - 1, j])
  27.                 return WriteLCS(c, s1, s2, i, j - 1);
  28.             else
  29.                 return WriteLCS(c, s1, s2, i - 1, j);
  30.         }
  31.         static void Main(string[] args)
  32.         {
  33.             string s1 = "ABCBDAB";
  34.             string s2 = "BDCABA";
  35.             int[,] c = LongestCommonSubsequence(s1, s2);
  36.             Console.WriteLine(WriteLCS(c,s1,s2,s1.Length,s2.Length));
  37.  
  38.  
  39.             Console.ReadKey();
  40.         }
  41.     }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement