Skip to content

Commit 641f0ee

Browse files
authored
Merge pull request #150 from xulongjun/patch-1
Create Edit-Distance.cs
2 parents fb23242 + f270611 commit 641f0ee

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
public class Solution {
2+
public int MinDistance(string word1, string word2) {
3+
int m = word1.Length;
4+
int n = word2.Length;
5+
int[,] dp = new int[2, n + 1];
6+
7+
for (int i = 0; i <= n; i++)
8+
dp[0, i] = i;
9+
10+
for (int i = 1; i <= m; i++)
11+
{
12+
for (int j = 0; j <= n; j++)
13+
{
14+
if (j == 0)
15+
dp[i % 2, j] = i;
16+
17+
else if (word1[i - 1] == word2[j - 1])
18+
dp[i % 2, j] = dp[(i - 1) % 2, j - 1];
19+
20+
else
21+
dp[i % 2, j] = 1 + Math.Min(Math.Min(dp[i % 2, j - 1], // Insert
22+
dp[(i - 1) % 2, j]), // Remove
23+
dp[(i - 1) % 2, j - 1]); // Replace
24+
}
25+
}
26+
27+
return dp[m % 2, n];
28+
}
29+
}

0 commit comments

Comments
 (0)