您的位置:首页 > 编程语言 > C语言/C++

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

2017-08-09 17:02 417 查看
算法实现比较简单,但算法原理不明白,有空了再研究一下。

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];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: