Skip to content

Commit 3a001ad

Browse files
committed
"Edit Distance"
1 parent 143683e commit 3a001ad

File tree

2 files changed

+54
-1
lines changed

2 files changed

+54
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ them with C++ Language.
1919
| 63 | [Unique Paths II] | [C](src/63.c) |
2020
| 64 | [Minimum Path Sum] | [C](src/64.c) |
2121
| 70 | [Climbing Stairs] | [C](src/70.c) |
22-
| 72 | [Edit Distance] | |
22+
| 72 | [Edit Distance] | [C](src/72.c) |
2323
| 85 | [Maximal Rectangle] | |
2424
| 87 | [Scramble String] | |
2525
| 91 | [Decode Ways] | [C](src/91.c) |

src/72.c

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
#include <string.h>
4+
5+
int min(int a, int b, int c) {
6+
int min = a;
7+
if (b < min) min = b;
8+
if (c < min) min = c;
9+
return min;
10+
}
11+
12+
int minDistance(char *word1, char *word2) {
13+
int len1 = strlen(word1);
14+
int len2 = strlen(word2);
15+
16+
/* these two lines can be commented out */
17+
if (len1 == 0) return len2;
18+
if (len2 == 0) return len1;
19+
20+
int(*d)[len2 + 1] = (int (*)[len2 + 1])calloc((len1 + 1) * (len2 + 1), sizeof(int));
21+
int i, j;
22+
23+
d[0][0] = 0; /* dummy */
24+
for (i = 1; i <= len1; i++) d[i][0] = i;
25+
for (j = 1; j <= len2; j++) d[0][j] = j;
26+
27+
for (i = 1; i <= len1; i++){
28+
for (j = 1; j <= len2; j++) {
29+
/* d[i][j] represents distance of word1[0..i-1] and word2[0..j-1] */
30+
if (word1[i - 1] == word2[j - 1]) {
31+
d[i][j] = d[i - 1][j - 1];
32+
}
33+
else {
34+
d[i][j] = min(
35+
d[i][j - 1] + 1, /* insert a character(word2[j-1]) to the tail of word1[0..i-1] */
36+
d[i - 1][j] + 1, /* delete a character(word1[i-1]) from the tail of word1[0..i-1] */
37+
d[i - 1][j - 1] + 1 /* replace a character in tail of word1[0..i-1] */
38+
);
39+
}
40+
}
41+
}
42+
return d[len1][len2];
43+
}
44+
45+
int main() {
46+
printf("%d %d\n", minDistance("word", "wood"), 1);
47+
printf("%d %d\n", minDistance("word", "woord"), 1);
48+
printf("%d %d\n", minDistance("d", "word"), 3);
49+
printf("%d %d\n", minDistance("", "word"), 4);
50+
printf("%d %d\n", minDistance("abcd", "word"), 3);
51+
printf("%d %d\n", minDistance("ffff", "word"), 4);
52+
return 0;
53+
}

0 commit comments

Comments
 (0)