编辑距离

/*
#author:zhuqi,2123419
#date:Dec 3,2014
#algorithm
#to produce the editdistance
#example:input:
         str1=EXPONEN-TIAL
         str2=--POLYNOMIAL
		 output:
		 editdistance=6
#example:input:
         str1=S-NOWY
         str2=SUNN-Y
		 output:
		 editdistance=3
#example:input:
         str1=-SNOW-Y
         str2=SUN--NY
		 output:
		 editdistance=5
*/

#include <iostream>
#include <string>

using namespace std;

int min(int a, int b)
{
    return a < b ? a : b;
}

int EditDistance(string str1, string str2)
{
    int max1 = str1.size();
    int max2 = str2.size();
    int edit[max1+1][max2+1];//edit[i][j]表示第一个字符串的长度i的子串到第二个字符串的长度为j的子串的编辑距离 
    /*分配存储空间 (数组分配也可以是动态的) 
	int **edit = new int*[max1 + 1];
    for(int i = 0; i < max1 + 1 ;i++)
    {
        edit[i] = new int[max2 + 1];
    }
    */
    //1.初始化 
    for(int i = 0 ;i < max1 + 1 ;i++)
    {
        edit[i][0] = i;
    }
    

    for(int i = 0 ;i < max2 + 1;i++)
    {
        edit[0][i] = i;
    }
    
    //2.求编辑距离 
    for(int i = 1 ;i < max1 + 1 ;i++)
    {
        for(int j = 1 ;j< max2 + 1; j++)
        {
            int d;//当第一个字符串的第i个字符不等于第二个字符串的第j个字符时,d=1,否则d=0 
            int temp = min(edit[i-1][j] + 1, edit[i][j-1] + 1);//比较添加一个字符和删除一个字符的情况 
            if(str1[i-1] == str2[j-1])
            {
                d = 0 ;
            }
            else
            {
                d = 1 ;
            }
            edit[i][j] = min(temp, edit[i-1][j-1] + d);//将修改一个字符的情况和之前添加和删除较小的情况进行比较 
        }
    }

    //3.输出编辑距离情况 
    cout << "**************************************" << endl;
    for(int i = 0 ;i < max1 + 1 ;i++)
    {
        for(int j = 0; j< max2 + 1; j++)
        {
            cout << edit[i][j] << " " ;
        }
        cout << endl;
    }
    cout << "**************************************" << endl;
    int editdistance = edit[max1][max2];//edit[max1][max2]即为所求str1和str2的编辑距离 
    /*撤销存储空间 
    for(int i = 0; i < max1 + 1; i++)
    {
        delete[] edit[i];
        edit[i] = NULL;
    }

    
	delete[] edit;
    edit = NULL;
    */
    
    return editdistance;
}

int main()
{
    string str1;
    string str2;
    cout<<">>>Find The Editdistance<<<"<<endl; 
    cout<<"Please input str1 :"<<endl;
    cin>>str1;
    cout<<"Please input str2 :"<<endl;
    cin>>str2;

    int editdistance = EditDistance(str1, str2);
    cout << "The editdistance is : " << editdistance << endl;

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值