Guest User

Untitled

a guest
Jan 16th, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.03 KB | None | 0 0
  1. using System;
  2.  
  3. class Solution
  4. {
  5. public static int DeletionDistance(string str1, string str2) // heat, hit
  6. {
  7. if(str1 == null && str2 == null) // false
  8. {
  9. return 0;
  10. }
  11.  
  12. if(str1 == null) // false
  13. {
  14. return str2.Length;
  15. }
  16.  
  17. if(str2 == null) // false
  18. {
  19. return str1.Length;
  20. }
  21.  
  22. var length1 = str1.Length; // 4
  23. var length2 = str2.Length; // 3
  24.  
  25. var deletionDistance = new int[length1 + 1, length2 + 1];
  26.  
  27. for(int col = 0; col < length2 + 1; col++) // base case
  28. {
  29. deletionDistance[0, col] = col;
  30. }
  31.  
  32. for(int row = 0; row < length1 + 1; row++)
  33. {
  34. deletionDistance[row, 0] = row;
  35. }
  36.  
  37. for(int row = 1; row < length1 + 1; row++)
  38. {
  39. for(int col = 1; col < length2 + 1; col++)
  40. {
  41. // it is equal
  42. var firstChar = str1[row - 1]; // heat -> left -> right
  43. var secondChar = str2[col - 1]; //hit
  44.  
  45. var isSame = firstChar == secondChar;
  46. if(isSame)
  47. {
  48. deletionDistance[row, col] = deletionDistance[row - 1, col - 1];
  49. }
  50. else
  51. {
  52. deletionDistance[row, col] = 1 + Math.Min(deletionDistance[row - 1, col], deletionDistance[row, col - 1]);
  53. }
  54. }
  55. }
  56.  
  57. return deletionDistance[length1, length2];
  58. }
  59.  
  60. static void Main(string[] args)
  61. {
  62. Console.WriteLine(DeletionDistance("heat","hit"));
  63. }
  64. }
  65.  
  66. /*
  67.  
  68. ---------------------
  69. |
  70. |
  71. | ^
  72. | <
  73.  
  74. heat = length1
  75. hit = length2
  76.  
  77. 0 1 2 3 4 total length = length1 + 1, 0 - length1
  78. "" t at eat heat
  79. 0
  80. 1 u
  81. 2 l ?
  82. 3
  83. ..
  84. .
  85. length2 + 1
  86.  
  87. base case:
  88. one thing is empty, distance
  89.  
  90. both distance 0
  91.  
  92. subproblem
  93.  
  94. say that dynamic programming today
  95.  
  96. h -> 0
  97. eat -> 1 + Math.Min(dist("at", "it"), dist("eat", "t"))
  98. it ->
  99.  
  100. ht
  101.  
  102. dog
  103. frog
  104.  
  105. d, f
  106. og-> frog
  107. f, r -> 3
  108.  
  109. some some
  110. 0
  111.  
  112. some thing
  113.  
  114. 4 + 5 = 9
  115. "" "" 0
  116. */
Add Comment
Please, Sign In to add comment