#include #define LONG long
#define CHAR char
#define N 100
/*求出三者中的最小值并返回*/
LONG Min ( LONG a, LONG b, LONG c )
{
if ( a > b ) a = b;
return a = a > c ? c: a;
}
/*利用动态规划求出字符串间的距离*/
LONG Distance ( CHAR string1[], CHAR string2[] )
{
LONG i, j, n, m;
LONG dis[strlen(string1) + 1][strlen(string2) + 1]; /*定义一个二级数组,用来表示string1[i]到string2[j]的距离*/
memset ( dis, 0, sizeof(dis) );
n = strlen(string1);
m = strlen(string2);
for ( i = 0, j = 0; j <= m; j++ ) dis[i][j] = j; /*当string1没有字符时,dis[0][j]距离就是string2的长度*/
for ( i = 1, j = 0; i <= n; i++ ) dis[i][j] = i; /*当string2没有字符时,dis[i][0]距离就是string1的长度*/
for ( i = 1; i <= n; i++ )
{
for ( j = 1; j <= m; j++ )
{
if ( string1[i] == string2[j] )
{
dis[i][j] = dis[i-1][j-1]; /*如果string1的第i个字符和string2的第j个字符相同,则dis[i][j] = dis[i-1][j-1]*/
}
else
{
dis[i][j] = Min ( dis[i-1][j], dis[i-1][j-1], dis[i][j-1] ) + 1; /*若字符不同,则从三种操作中选择次数最小的操作*/
}
}
}
return dis[n][m];
}
void main()
{
CHAR string1[N] = "";
CHAR string2[N] = "";
printf ( "请输入字符串1和字符串2(回车间隔):\n" );
gets ( string1 );
gets ( string2 );
printf ( "需要进行 %d 次操作。\n", Distance ( string1, string2 ) );
return;
}