MeGaDeTH_91

Longest Common Subsequence

Jun 6th, 2019
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.12 KB | None | 0 0
  1. namespace _02.LongestCommonSeq
  2. {
  3. using System;
  4. using System.Linq;
  5.  
  6. public class StartUp
  7. {
  8. private static int[][] lcs;
  9. private static char[] firstWord;
  10. private static char[] secondWord;
  11.  
  12. public static void Main()
  13. {
  14. ReadInputInitialize();
  15.  
  16. CountLCS();
  17.  
  18. PrintResult();
  19. }
  20.  
  21. private static void ReadInputInitialize()
  22. {
  23. firstWord = Console.ReadLine().ToCharArray();
  24. secondWord = Console.ReadLine().ToCharArray();
  25.  
  26. lcs = new int[firstWord.Length + 1][];
  27.  
  28. for (int row = 0; row < lcs.Length; row++)
  29. {
  30. lcs[row] = new int[secondWord.Length + 1];
  31. }
  32. }
  33.  
  34. private static void PrintResult()
  35. {
  36. int max = 0;
  37.  
  38. for (int row = 0; row < lcs.Length; row++)
  39. {
  40. int currentMax = lcs[row].Max();
  41. if(currentMax > max)
  42. {
  43. max = currentMax;
  44. }
  45. }
  46.  
  47. Console.WriteLine(max);
  48. }
  49.  
  50. private static void CountLCS()
  51. {
  52. for (int row = 1; row < lcs.Length; row++)
  53. {
  54. for (int col = 1; col < lcs[row].Length; col++)
  55. {
  56. char leftLetter = firstWord[row - 1];
  57. char rightLetter = secondWord[col - 1];
  58.  
  59. int leftTopElement = lcs[row - 1][col - 1];
  60. int topElement = lcs[row - 1][col];
  61. int leftElement = lcs[row][col - 1];
  62.  
  63. if (leftLetter == rightLetter)
  64. {
  65. lcs[row][col] = leftTopElement + 1;
  66. }
  67. else if(topElement > leftElement)
  68. {
  69. lcs[row][col] = topElement;
  70. }
  71. else
  72. {
  73. lcs[row][col] = leftElement;
  74. }
  75. }
  76. }
  77. }
  78. }
  79. }
Advertisement
Add Comment
Please, Sign In to add comment