计算字符串的距离
题目描述
Levenshtein 距离,又称编辑距离,指的是两个字符串之间,由一个转换成另一个所需的最少编辑操作次数。许可的编辑操作包括将一个字符替换成另一个字符,插入一个字符,删除一个字符。编辑距离的算法是首先由俄国科学家Levenshtein提出的,故又叫Levenshtein Distance。
Ex:
字符串A:abcdefg
字符串B: abcdef
通过增加或是删掉字符”g”的方式达到目的。这两种方案都需要一次操作。把这个操作所需要的次数定义为两个字符串的距离。
要求:
给定任意两个字符串,写出一个算法计算它们的编辑距离。
请实现如下接口
/* 功能:计算两个字符串的距离
* 输入:字符串A和字符串B
* 输出:无
* 返回:如果成功计算出字符串的距离,否则返回-1
*/
public static int calStringDistance (String charA, String charB)
{
return 0;
}
输入描述:
输入两个字符串
输出描述:
得到计算结果
输入例子:
abcdefg
abcdef
输出例子:
1
解答代码:
#include<iostream>
#include <cstring>
#include <cstdio>
#include <cstdlib>
using namespace std;
int dp[512][512];//构造一张表
int Min(int a,int b,int c)
{
int tmp=b>c?c:b;
return a>tmp?tmp:a;
}
int calStringDistance (char str1[],char str2[])
{
int len1,len2,i,j;
len1 = strlen(str1);
len2 = strlen(str2);
int temp1,temp2,temp3,temp;
dp[0][0] = 0;
//按行和列初始化
for(j=1; j<len2+1; j++)
{
dp[0][j] = j;
}
for(i=1; i<len1+1; i++)
{
dp[i][0] = i;
}
for(i=1; i<len1+1; i++)
{
for(j=1; j<len2+1; j++)
{
temp1 = dp[i-1][j]+1; // 增加一个或者删除一个
temp2 = dp[i][j-1]+1; // 增加一个或者删除一个
if(str1[i-1]==str2[j-1])
temp3 = dp[i-1][j-1];
else
temp3 = dp[i-1][j-1]+1;
temp = Min(temp1,temp2,temp3);
dp[i][j] = temp;
}
}
return dp[len1][len2];
}
int main()
{
char str1[500],str2[500];
int res;
while(scanf("%s",&str1)!=EOF)
{
scanf("%s",&str2);
res = calStringDistance (str1,str2);
printf("%d\n",res);
}
return 0;
}