两个字符串的编辑距离
参考网上的实现
// project1.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include<string.h> #define LENGTH 100 //两个字符串的编辑距离 //编辑距离就是将两个字符串变成相同字符串所需要的最小操作次数 //纯暴力搜索法,复杂度O(N*M) int calEditDist(char strX[],int begX,int endX,char *strY,int begY,int endY){ if(endX==0){ if(endY==0) return 0; else return endY-begY+1; } if(endY==0){ if(endX==0) return 0; else return endX-begX+1; } if(strX[endX]==strY[endY]) return calEditDist(strX,begX,endX-1,strY,begY,endY-1); else{ int t1 = calEditDist(strX,begX,endX-1,strY,begY,endY); int t2 = calEditDist(strX,begX,endX,strY,begY,endY-1); int t3 = calEditDist(strX,begX,endX-1,strY,begY,endY-1); t1 = t1 < t2 ? t1 : t2; return (t1 < t3 ? t1 : t3) + 1; } } //针对暴力方法的改进,利用空间换时间 //依然自顶向下 int dp[LENGTH][LENGTH];//备忘数组,注意要放在函数外 int calEditDist_opt(char strX[],int begX,int endX,char *strY,int begY,int endY){ if(endX == 0){ if(endY == 0) return 0; else return endY - begY + 1; } if(endY == 0){ if(endX == 0) return 0; else return endX - begX + 1; } if(strX[endX] == strY[endY]){ if(dp[endX-1][endY-1] == 0) dp[endX-1][endY-1] = calEditDist_opt(strX,begX,endX-1,strY,begY,endY-1); return dp[endX-1][endY-1]; } else{ int t1, t2, t3; if(dp[endX-1][endY] == 0) dp[endX-1][endY] = calEditDist_opt(strX,begX,endX-1,strY,begY,endY); t1 = dp[endX-1][endY]; if(dp[endX][endY-1] == 0) dp[endX][endY-1] = calEditDist_opt(strX,begX,endX,strY,begY,endY-1); t2 = dp[endX][endY-1]; if(dp[endX-1][endY-1] == 0) dp[endX-1][endY-1] =calEditDist_opt(strX,begX,endX-1,strY,begY,endY-1); t3 = dp[endX-1][endY-1]; t1 = t1 < t2 ? t1 : t2; return (t1 < t3 ? t1 : t3) + 1; } } //方法3,自底向上 int dp2[LENGTH][LENGTH];//表示strX[0..i]与strY[0..j]的编辑距离 int calEditDist_opt_two(char strX[],int begX,int endX,char *strY,int begY,int endY) { int i, j; for(i = begX; i <= endX; ++i) dp2[i][0] = i+1; for(j = begY; j <= endY; ++j) dp2[0][j] = j+1; for(i = begX+1; i <= endX; ++i){ for(j = begY+1; j <= endY; ++j){ if(strX[i] == strY[j]) dp2[i][j] = dp2[i-1][j-1]; else{ int t1 = dp2[i-1][j]; t1 = t1 < dp2[i][j-1] ? t1 :dp2[i][j-1]; t1 = t1 < dp2[i-1][j-1] ? t1 : dp2[i-1][j-1]; dp2[i][j] = t1 + 1; } } } return dp2[endX][endY]; } int _tmain(int argc, _TCHAR* argv[]) { char str1[LENGTH]="abbaeaabccbaeeaee"; char str2[LENGTH]="aaaaaaaaa"; char str3[LENGTH]="abababababab"; printf("%d\n",calEditDist(str1,0,strlen(str1)-1,str3,0,strlen(str3)-1)); printf("%d\n",calEditDist_opt(str1,0,strlen(str1)-1,str3,0,strlen(str3)-1)); printf("%d\n",calEditDist_opt_two(str1,0,strlen(str1)-1,str3,0,strlen(str3)-1)); return 0; }