问题描述:设S1和S2是两个字符串。要用最少的字符操作将字符串S1转换为字符串S2。这里的字符串操作包括:
(1)删除一个字符
(2)插入一个字符
(3)将一个字符改成为另一个字符。
将字符串S1转换为字符串S2的所用的最少的字符串操作数称作字符串S1到S2的最短距离,记为 d(S1, S2).
算法设计:给定字符串S1和S2,计算它们的最短编辑距离d(S1, S2)。
这是本人在VC6.0编译通过的一个实现代码:
#include " stdafx.h "
#include < iostream.h >
int min( int , int , int );
int dist( char * , char * );
int length( char * );
int main( int argc, char * argv[])
{
char * a = " This is a test! " ;
char * b = " That is not true " ;
cout << dist(a, b) << endl;
return 0 ;
}
int min( int a, int b, int c)
{
int temp = (a < b ? a : b);
return (temp < c ? temp : c);
}
{
int temp = 0;
while(*str != '/0')
{
temp++;
str++;
}
return temp;
}
int dist(char* a, char* b)
{
int m = length(a);
int n = length(b);
int* d = new int[n + 1];
for(int i = 0; i <= n; i++)
d[i] = i;
for(i = 1; i <= m; i++)
{
int y = i - 1;
for(int j = 1; j <=n; j++)
{
int x = y;
y = d[j];
int z = (j > 1 ? d[j - 1] : i);
int del = (a[i - 1] == b[j - 1] ? 0 : 1);
d[j] = min(x + del, y + 1, z + 1);
}
}
int temp = d[n];
delete[] d;
return temp;
}