zoukankan      html  css  js  c++  java
  • LD算法的C++实现(基于编辑距离的文本比较算法)

    算法看这里:

    http://www.cnblogs.com/grenet/archive/2010/06/01/1748448.html

    用数组实现:

     1 #include <iostream>
     2 #include <stdio.h>
     3 #include <string>
     4 using namespace std;
     5 
     6 //LD算法(Levenshtein Distance)又成为编辑距离算法(Edit Distance)。他是以字符串A通过插入字符、删除字符、替换字符变成另一个字符串B,那么操作的过程的次数表示两个字符串的差异。
     7 
     8 void cal(int count[][100], char s1[], char s2[], int i, int j){                //注意这里:传入二维数组时,最低维必须指定维数!!
     9     if(s1[i]==s2[j]){
    10         count[i][j] = count[i-1][j-1];
    11     }
    12     else {
    13         int min = count[i-1][j-1]<count[i-1][j] ? count[i-1][j-1] : count[i-1][j];
    14         min = min<count[i][j-1] ? min : count[i][j-1];
    15         count[i][j] = min+1;
    16     }
    17     //cout<<sizeof(count)<<endl;            //输出貌似还是4 这就是一个指针的大小了吧?
    18 }
    19 
    20 int LD(char s1[], char s2[], int len1, int len2){
    21     int i,j;
    22     
    23     //cout<<strlen(s1)<<strlen(s2)<<endl;        //可以得到正确的长度
    24     //cout<<sizeof(s1)<<sizeof(s2)<<endl;        //输出一直是4!可能是因为变成了指针?
    25     //cout<<sizeof(s1[0])<<sizeof(s2[0])<<endl;
    26     //cout<<len1<<len2<<endl;
    27     //cout<<s1[0]<<s2[0]<<endl;
    28     //cout<<s1<<s2<<endl;
    29     int count[100][100];                    //声明数组!维数不能是变量!
    30     //int count[len1+1][len2+1];            //这样编译不通过!
    31     for(i=0; i<len2+1; i++){
    32         count[0][i] = i;
    33     }
    34     for(i=0;i<len1+1;i++){
    35         count[i][0] = i;
    36     }
    37 
    38     for(i=1; i<len1+1;i++){
    39         for(j=1; j<len2+1; j++){
    40             cal(count,s1,s2,i,j);
    41         }
    42     }
    43     for(i=0;i<len1+1;i++){
    44         for(j=0;j<len2+1;j++){
    45             cout<<count[i][j]<<" ";
    46         }
    47         cout<<endl;
    48     }
    49     return count[len1][len2];
    50 }
    51 
    52 int main(){
    53 
    54     char s1[100]; //= "ABSDFADFSF";
    55     char s2[100];// = "ASFDSGGGHFH";
    56     while(scanf("%s%s",s1,s2)!=EOF){
    57         int len1 = strlen(s1);
    58         int len2 = strlen(s2);
    59         int result = LD(s1,s2,len1,len2);
    60         cout<<result<<endl;
    61     }
    62     return 0;
    63     
    64 }
  • 相关阅读:
    DataGridView重绘painting简单实例
    C#实现万年历(农历、节气、节日、星座、属相、生肖、闰年等)
    《开源框架那点事儿11》:软件开发杂谈
    半年总结——欲戴王冠,必承其重
    三天学会HTML5 之第一天
    读书笔记 -《高效程序猿的45个习惯-敏捷开发修炼之道》
    Opengl ES 1.x NDK实例开发之七:旋转的纹理立方体
    我与小娜(08):人工智能的伟大胜利
    阿里云 oss 小文件上传进度显示
    模仿猫眼电影App一个动画效果
  • 原文地址:https://www.cnblogs.com/haoyijing/p/5731887.html
Copyright © 2011-2022 走看看