zoukankan      html  css  js  c++  java
  • 【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];
    }
  • 相关阅读:
    层模型--绝对定位(position:absolute)
    什么是层模型?
    浮动模型
    流动模型(二)
    插值方法
    CFS调度分析(内核版本:2.6.34)
    CRC检验
    ubuntu误删home目录
    随想
    Android——Activity生命周期
  • 原文地址:https://www.cnblogs.com/quark/p/7326319.html
Copyright © 2011-2022 走看看