Implementing the Algorithm
To implement the dynamic programming algorithm for calculating edit distance, we can follow these steps:
- Create a 2D matrix
dp
with dimensions based on the lengths of the two input strings.
TEXT/X-CSHARP
1{code}
In this code snippet, we have a CalculateEditDistance
method that takes two strings str1
and str2
as input.
- Initialize the first row and first column of the
dp
matrix with incremental values representing the number of deletions or insertions required.
TEXT/X-CSHARP
1for (int i = 0; i <= str1.Length; i++) {
2 dp[i, 0] = i;
3}
4
5for (int j = 0; j <= str2.Length; j++) {
6 dp[0, j] = j;
7}
In these loops, we set the values in the first row and first column of the matrix to represent the cost of deleting or inserting characters.
- Iterate over each cell of the
dp
matrix, comparing the characters of the substrings. If the characters match, the value in the current cell is set to the value in the diagonal cell. If the characters don't match, the value in the current cell is set to the minimum value among the adjacent cells plus 1 (representing the cost of substitution).
TEXT/X-CSHARP
1for (int i = 1; i <= str1.Length; i++) {
2 for (int j = 1; j <= str2.Length; j++) {
3 if (str1[i - 1] == str2[j - 1]) {
4 dp[i, j] = dp[i - 1, j - 1];
5 }
6 else {
7 dp[i, j] = Math.Min(dp[i - 1, j - 1] + 1, Math.Min(dp[i, j - 1] + 1, dp[i - 1, j] + 1));
8 }
9 }
10}
In these nested loops, we iterate over each cell of the matrix and update its value based on the comparison of characters.
- Finally, we return the value in the bottom-right cell of the
dp
matrix, which represents the edit distance between the two input strings.
That's how we can implement the dynamic programming algorithm to calculate edit distance.
xxxxxxxxxx
35
}
using System;
class EditDistance {
public static int CalculateEditDistance(string str1, string str2) {
int[,] dp = new int[str1.Length + 1, str2.Length + 1];
for (int i = 0; i <= str1.Length; i++) {
dp[i, 0] = i;
}
for (int j = 0; j <= str2.Length; j++) {
dp[0, j] = j;
}
for (int i = 1; i <= str1.Length; i++) {
for (int j = 1; j <= str2.Length; j++) {
if (str1[i - 1] == str2[j - 1]) {
dp[i, j] = dp[i - 1, j - 1];
}
else {
dp[i, j] = Math.Min(dp[i - 1, j - 1] + 1, Math.Min(dp[i, j - 1] + 1, dp[i - 1, j] + 1));
}
}
}
return dp[str1.Length, str2.Length];
}
public static void Main(string[] args) {
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment