【Algorithm】字符串编辑距离(Levenshtein距离)C++算法实现

时间:2023-03-09 06:45:33
【Algorithm】字符串编辑距离(Levenshtein距离)C++算法实现

算法实现比较简单,但算法原理不明白,有空了再研究一下。

unsigned LevenshteinDistance(const string& s1, const string& s2)
{
if (s1.empty()) {
return (unsigned)s2.size();
} if (s2.empty()) {
return (unsigned)s1.size();
} unsigned row = (unsigned)s1.size() + 1;
unsigned col = (unsigned)s2.size() + 1; auto_ptr<unsigned> apBuf(new unsigned[row * col]); unsigned* pBuf = apBuf.get(); for (unsigned i=0; i < row; ++i) {
pBuf[i * col] = i;
} for (unsigned i=0; i < col; ++i) {
pBuf[i] = i;
} for (unsigned i=1; i < row; ++i) {
for (unsigned j = 1; j < col; ++j) { unsigned temp = (s1[i-1] == s2[j-1]) ? 0 : 1; pBuf[i * col + j] = min( min( pBuf[(i-1) * col + j] + 1, pBuf[i * col + j - 1] + 1 ), (pBuf[(i -1 ) * col + j - 1] + temp) );
}
} // dump buf
for (unsigned i=0; i < row; ++i) {
for (unsigned j= 0; j < col; ++j) {
cout << pBuf[i * col + j] << " ";
}
cout << endl;
} return pBuf[row * col - 1];
}