題目來自編程之美
題目
思路:其實就是求兩個字符串的編輯距離,直接給出DP的思路
代碼
#include <iostream>
#include <assert.h>
#include <string>
using namespace std;
/*
f[i][j]:表示字符串A[1~i]轉換成B[1~j]的最小編輯距離
f[i][j] = min{f[i - 1][j - 1] + value,f[i][j - 1] + 1,f[i - 1][j] + 1};其中A[i] = B[j],則value = 0,否則value = 1
初始化:f[0][j] = j;f[i][0] = i
結果:f[nLenA - 1][nLenB - 1]
*/
int f[50][50];
int Min(int x,int y,int z)
{
if (x < y)
{
if (x < z)
{
return x;
}
else
{
return z;
}
}
else
{
if (y < z)
{
return y;
}
else
{
return z;
}
}
}
int EditDistance(char* pStrA,char* pStrB)
{
assert(pStrA && pStrB);
int nLenA = strlen(pStrA);
int nLenB = strlen(pStrB);
int nValue = 0;
//初始化
for (int i = 0;i < nLenA;i++)
{
f[i][0] = i;
}
for (int j = 0;j < nLenB;j++)
{
f[0][j] = j;
}
for (int i = 1;i < nLenA;i++)
{
for (int j = 1;j < nLenB;j++)
{
nValue = 1;
if (pStrA[i] == pStrB[j])
{
nValue = 0;
}
f[i][j] = Min(f[i - 1][j - 1] + nValue,f[i][j - 1] + 1,f[i - 1][j] + 1);
}
}
return f[nLenA - 1][nLenB - 1];
}
int main()
{
char strA[50];
char strB[50];
string str;
//輸入字符串A
cin>>str;
strA[0] = ' ';
for (int i = 0;i < str.size();i++)
{
strA[i + 1] = str[i];
}
strA[str.size() + 1] = 0;
//輸入字符串A
cin>>str;
strB[0] = ' ';
for (int i = 0;i < str.size();i++)
{
strB[i + 1] = str[i];
}
strB[str.size() + 1] = 0;
int nSimNum = EditDistance(strA,strB);
cout<< 1.0 / (nSimNum + 1)<<endl;
system("pause");
return 1;
}