int calcstrdis(char * src, char * des, int srclength, int deslength) { int i(0); int j(0); int tempresult(0); int ** rss = new int *[deslength + 1]; for (i = 0; i <= deslength; ++ i) rss[i] = new int[srclength + 1]; for (i = 0; i <= deslength; ++ i) rss[i][0] = i; for (i = 0; i <= srclength; ++ i) rss[0][i] = i; for (i = 1; i <= deslength; ++ i) for (j = 1; j <= srclength; ++ j) if (des[i] == src[j]) rss[i][j] = rss[i - 1][j - 1]; else { tempresult = rss[i - 1][j - 1]; tempresult = tempresult < rss[i - 1][j] ? tempresult : rss[i - 1][j]; tempresult = tempresult < rss[i][j - 1] ? tempresult : rss[i][j - 1]; rss[i][j] = tempresult + 1; } tempresult = rss[deslength][srclength]; for (i = 0; i <= deslength; ++ i) delete[] rss[i]; delete[] rss; return tempresult; }
测试
#include <iostream> using namespace std; int main() { char * src = "snowyk"; char * des = "asunnyk"; cout << calcstrdis(src, des, strlen(src), strlen(des)) << endl; return 0; }