模糊匹配算法


項目中需要對車牌號碼進行模糊匹配,比如5位數相同就認為車牌號碼匹配成功。

 

參考:

字符串模糊匹配使用遞歸實現 - CSDN博客  http://blog.csdn.net/damenggege123/article/details/8213500

字符串模糊匹配遞歸實現優化1 - CSDN博客  http://blog.csdn.net/damenggege123/article/details/8213919

實際上我的實現就是將上面博客中的java代碼改成了c++代碼而已,所以非常感謝上面的博主!

下面是修改后的C++實現:

.h文件:

#include <string>
using namespace std;

class CMatch
{
public:
CMatch();
~CMatch();

public:

/**
* 百分之多少之內匹配錯誤可以接受
* a與ab匹配為百分之50的錯誤率。
* @param percent 設置匹配百分比
* @param src 字符串1
* @param dest 字符串2
* @param hander 匹配規則
* @return
*/
bool Match(double percent,string src,string dest);

/**
* 幾個錯誤的字符可以接受
* a與ab為1個字符錯誤可以接受
* @param percent 設置匹配百分比
* @param src 字符串1
* @param dest 字符串2
* @param hander 匹配規則
* @return
*/
bool Match(int errorNum, string src,string dest);

private:
int CalcMatchNumber(string src, int i, string dest, int j, int curdeep,int maxdeep);

};

 

 

.cpp文件

#include "Match.h"
#include <math.h>


CMatch::CMatch()
{

}


CMatch::~CMatch()
{

}

bool CMatch::Match( double percent,string src,string dest )
{

int score = 0;
int max = src.size() > dest.size() ? src.size(): dest.size();
score = CalcMatchNumber(src, 0, dest, 0, 0, (int)ceil((1-percent)*max) );

return score/max > percent;

}

bool CMatch::Match( int errorNum, string src,string dest )
{


int score = CalcMatchNumber(src, 0, dest, 0, 0, errorNum );
int max = src.size() > dest.size() ? src.size(): dest.size();
return max - score <= errorNum;

}

int CMatch::CalcMatchNumber( string src, int i, string dest, int j, int curdeep,int maxdeep )
{

 

int score = 0;
if( curdeep > maxdeep ||i >= src.size() || j >= dest.size())
return 0;
//bool ismatch = hander.compare(csrc[i], cdest[j]);

if( src[i] == dest[j] )
{
score++;
if(i+1<src.size() && j+1<dest.size())
{
score += CalcMatchNumber(src, i+1, dest, j+1, 0,maxdeep);
}

}
else
{
int temp1 = 0;
int temp2 = 0;
int temp3 = 0;
temp1 += CalcMatchNumber(src, i, dest, j+1, curdeep+1,maxdeep) ;
temp2 += CalcMatchNumber(src, i+1, dest, j, curdeep+1,maxdeep) ;
temp3 += CalcMatchNumber(src, i+1, dest, j+1, curdeep+1,maxdeep) ;
int temp4 = std::max(temp1, temp2);
score += std::max(temp3, temp4);
}
return score;

}

 

 

使用示例:

string str1 = "遼A56633";
string str2 = "遼A56635";
string str3 = "吉A54633";


CMatch matcher;
bool bRet = matcher.Match(5, str1, str3);

 

 

其他參考資料:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM