字符串编辑距离查表法

时空复杂度均为 O ( |s1| * |s2| )

unsigned int CalcStringDistance ( const _TCHAR str1[], unsigned int l1, const _TCHAR str2[], unsigned int l2, unsigned int* record, unsigned int rl ) { unsigned int r, left, top, topleft; if ( !l1 ) return l2; if ( !l2 ) return l1; r = record [ ( l2 - 1 ) * rl + l1 - 1 ]; if ( r ) return r; left = CalcStringDistance ( str1, l1 - 1, str2, l2, record, rl ); top = CalcStringDistance ( str1, l1, str2, l2 - 1, record, rl ); r = ( left > top ? top : left ) + 1; topleft = CalcStringDistance ( str1, l1 - 1, str2, l2 - 1, record, rl ); if ( str1[l1 - 1] != str2[l2 - 1] ) topleft++; if ( r > topleft ) r = topleft; record [ ( l2 - 1 ) * rl + l1 - 1 ] = r; return r; } unsigned int StringDistance ( const _TCHAR str1[], const _TCHAR str2[] ) { unsigned int l1 = _tcslen ( str1 ); unsigned int l2 = _tcslen ( str2 ); unsigned int* record = (unsigned int*)malloc(sizeof(unsigned int)*l1*l2); unsigned int result; memset ( record, 0, sizeof ( unsigned int ) * l1 * l2 ); result = CalcStringDistance ( str1, l1, str2, l2, record, l1 ); free ( record ); return result; }

参考:

《字符串编辑距离查表法改进》

你可能感兴趣的:(字符串编辑距离查表法)