44#include <string.h>
55
66/*
7- * Dynamic Programming
8- *
9- * Definitaion
10- *
11- * m[i][j] is minimal distance from word1[0..i] to word2[0..j]
12- *
13- * So,
14- *
15- * 1) if word1[i] == word2[j], then m[i][j] == m[i-1][j-1].
16- *
17- * 2) if word1[i] != word2[j], then we need to find which one below is minimal:
18- *
19- * min( m[i-1][j-1], m[i-1][j], m[i][j-1] )
20- *
21- * and +1 - current char need be changed.
22- *
23- * Let's take a look m[1][2] : "a" => "ab"
24- *
25- * +---+ +---+
26- * ''=> a | 1 | | 2 | '' => ab
27- * +---+ +---+
28- *
29- * +---+ +---+
30- * a => a | 0 | | 1 | a => ab
31- * +---+ +---+
32- *
33- * To know the minimal distance `a => ab`, we can get it from one of the following cases:
34- *
35- * 1) delete the last char in word1, minDistance( '' => ab ) + 1
36- * 2) delete the last char in word2, minDistance( a => a ) + 1
37- * 3) change the last char, minDistance( '' => a ) + 1
38- *
39- *
40- * For Example:
41- *
427 * word1="abb", word2="abccb"
438 *
449 * 1) Initialize the DP matrix as below:
5621 * a 1 0 1 2 3 4
5722 * b 2 1 0 1 2 3
5823 * b 3 2 1 1 2 2
59- *
6024 */
6125
26+ static inline int min (int a , int b )
27+ {
28+ return a < b ? a : b ;
29+ }
30+
6231static int minDistance (char * word1 , char * word2 )
6332{
6433 int i , j ;
@@ -82,9 +51,7 @@ static int minDistance(char* word1, char* word2)
8251 if (word1 [i - 1 ] == word2 [j - 1 ]) {
8352 dp [i ][j ] = dp [i - 1 ][j - 1 ];
8453 } else {
85- int min = dp [i - 1 ][j ] > dp [i ][j - 1 ] ? dp [i ][j - 1 ] : dp [i - 1 ][j ];
86- dp [i ][j ] = min > dp [i - 1 ][j - 1 ] ? dp [i - 1 ][j - 1 ] : min ;
87- dp [i ][j ] += 1 ;
54+ dp [i ][j ] = 1 + min (dp [i - 1 ][j - 1 ], min (dp [i - 1 ][j ], dp [i ][j - 1 ]));
8855 }
8956 }
9057 }
0 commit comments