quark

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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

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];
}
posted on 2017-08-09 17:02  QuarkZ  阅读(499)  评论(0编辑  收藏  举报