//递归解法 int CalStr(const char* Src, const char *Pattern) { assert(Src && Pattern); if(*Src == '\0') { return strlen(Pattern); } if(*Pattern == '\0') { return strlen(Src); } if(*Src == *Pattern) { return CalStr(Src + 1, Pattern + 1); } int t1 = CalStr(Src, Pattern + 1);//插入字符 int t2 = CalStr(Src + 1, Pattern + 1);//替换字符 int t3 = CalStr(Src + 1, Pattern);//删除字符 return min(t1, t2, t3) + 1; } //非递归解法,动态规划 int CalStrDP(const char *Src, const char *Pattern) { assert(Src && Pattern); memset(dp, 0, sizeof(int) * Max_N * Max_N); int nLen1 = strlen(Src); int nLen2 = strlen(Pattern); int i,j; for(i = nLen1 - 1; i >= 0; --i) { for(j = nLen2 - 1; j >= 0; --j) { if(Src[i] == Pattern[j]) { dp[i][j] = dp[i + 1][j + 1]; } else { if(i < nLen1 - 1 || j < nLen2 - 1)//如果在两个字符串的末尾,则默认初始值为0,直接计算 { if(i + 1 >= nLen1)//设置边界值 { dp[i + 1][j + 1] = Max_N; dp[i + 1][j] = Max_N; } if(j + 1 >= nLen2)//设置边界值 { dp[i][j + 1] = Max_N; dp[i + 1][j + 1] = Max_N; } } dp[i][j] = min(dp[i][j + 1], dp[i + 1][j + 1], dp[i + 1][j]) + 1; } } } return dp[0][0]; }
下面给出main函数和辅助函数:
#include<stdio.h> #include<string.h> #include<assert.h> const int Max_N = 100; int dp[Max_N][Max_N]; inline int min(const int a, const int b, const int c) { int t = a < b ? a : b; return t < c ? t : c; } int main() { char Src[Max_N]; char Pattern[Max_N]; while(gets(Src) && gets(Pattern)) { printf("递归:%d\n", CalStr(Src, Pattern)); printf("非递归:%d\n", CalStrDP(Src, Pattern)); } return 0; }