简单的字符串近似匹配

原理有空再写,其实就是动态规划

#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;
  }
 

 

 
}

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值