两个字符串编辑距离

来源:互联网 发布:linux下utf8转gbk 编辑:程序博客网 时间:2024/06/07 13:05
#include<cstdio>#include<cstring>#include<algorithm>using namespace std;const int maxn=1e3+5;//求字符串s->t的编辑距离int n,m;char s[maxn],t[maxn];int dp[maxn][maxn];void solve(){    int n=strlen(s+1);    int m=strlen(t+1);    memset(dp,0,sizeof(dp));    //第一列初始化    for(int i=0;i<=n;i++)    {        dp[i][0]=i;    }    //第一行初始化    for(int i=0;i<=m;i++)    {        dp[0][i]=i;    }    for(int i=1;i<=n;i++)    {        for(int j=1;j<=m;j++)        {            if(s[i]==t[j])//如果字符相同            {                dp[i][j]=dp[i-1][j-1];//为左上角的值            }            else//不相同            {                dp[i][j]=min(dp[i-1][j-1]+1,min(dp[i-1][j]+1,dp[i][j-1]+1));                //左上角的值+1,左边值+1,上面值+1,取三者最小值            }        }    }    printf("%d\n",dp[n][m]);}int main(){   while(~scanf("%s%s",s+1,t+1))   {       solve();   }   return 0;}