原理有空再写,其实就是动态规划
#include<iostream>
#include<string>
#include<cstdio>
#include <iomanip>
#define MAX 0XFFFFFFF
using namespace std;
int min(int a,int b,int c)
{
int t=a>b?b:a;
t=t>c?c:t;
return t;
}
int find(string p,string t,int &k)//目标字串是t,匹配的字串是p,k是设好的允许有不相同的地方最多有k出
{
int match[50][50]={0};//表明匹配的字串最多的长度就是是50
int i,j,lenP=p.length(),lenT=t.length();
for(i=0;i<=lenT;i++)
match[0][i]=0;
for(i=0;i<=lenP;i++)
match[i][0]=i;
for(j=1;j<=lenT;j++)
for(i=1;i<=lenP;i++)
{
if(t[j-1]==p[i-1])
match[i][j]=min(match[i-1][j-1],match[i-1][j]+1,match[i][j-1]+1);
else
match[i][j]=min(match[i-1][j-1]+1,match[i-1][j]+1,match[i][j-1]+1);
}
int Min=match[lenP][0],tt=-1;
for(i=1;i<=lenT;i++) //找到t串中与p相似的,差别不超过k的下坐标
if(match[lenP][i]<Min)
{
Min=match[lenP][i];
tt=i-1;
}
k=Min;//记录匹配的最小差别数
return tt;
}
int main()
{
string p="happy";
string t="Have a hsppy day";
cout<<"please input the string:";
getline(cin,p);
int i=0,j,m;
string arr[6]={
"i love my mom and father",
"I ove Mymom andfa ther",
" father and Mother" ,"f ather and moth er","Fath er","mother f a ther" };
int arrTarget[6]={-1};
int arrK[6];
for(i=0;i<6;i++)
{
arrTarget[i]=find(p,arr[i],arrK[i]);
}
cout<<"you want to match : "<<p<<endl;
cout<<"************************** after match the ans is********************"<<endl;
cout<<" 句子 匹配的最小差别数 下标\n";
for(i=0;i<6;i++)
{
m=i;
for(j=0;j<6;j++)
if(arrK[m]>arrK[j])
m=j;
cout<<left<<setw(50)<<arr[m]<<setw(10)<<arrK[m]<<setw(10)<<arrTarget[m]<<endl;
arrK[m]=MAX;
}
}
2307

被折叠的 条评论
为什么被折叠?



