[算法]简单的字符串近似匹配算法实现

GCC实现:

/****************************************************************************** * file: appmatch.cpp * brief: 字符串近似匹配算法实现 * 参照《柔性字符串匹配》6.2.2节 在文本中搜索 * creator: thinkhy * date: 2010-10-28 星期四 * ******************************************************************************/ #include <iostream> #include <fstream> #include <sstream> #include <string> #include <vector> #include <stack> #include <limits> using namespace std; int main() { ifstream fin("in1.txt"); ofstream out("out.txt"); stringstream ss; string keyword = "1.4.3 怎样编译Perl?"; ss << fin.rdbuf(); string text = ss.str(); vector<int> c1; // 距离矩阵第c[j-1]列 vector<int> c2; // 距离矩阵第c[j]列 c1.resize(keyword.size()+1); c2.resize(keyword.size()+1); for(int i = 0; i <= keyword.size(); i++) c1[i] = i; c2[0] = 0; int minStep = numeric_limits<int>::max(); int matchpos; for (int i = 1; i <= text.size(); i++) { for(int j = 1; j <= keyword.size(); j++) { c2[j] = c1[j-1] + (text[i-1] == keyword[j-1] ? 0 : 1); if (c2[j] > c1[j] + 1) c2[j] = c1[j] + 1; if (c2[j] > c2[j-1] + 1) c2[j] = c2[j-1] + 1; } for(int j = 1; j <= keyword.size(); j++) c1[j] = c2[j]; if (minStep >= c2[keyword.size()]) // 取最后一个最近似的子串 { minStep = c2[keyword.size()]; matchpos = i; } } cout << text << endl; cout << "keyword:" << keyword << endl; cout << "match text: " << text.substr(matchpos - keyword.size(), keyword.size()) << endl; cout << "match postion:" << matchpos << endl; getchar(); return 0; }

Visual Studio C++实现:

int ApproxMatch(const std::wstring& wstrText, const std::wstring& wstrPattern) { if (wstrPattern.empty() || wstrText.empty()) return -1; if (wstrPattern.size() > wstrText.size()) return -1; vector<int> arrC1; // 距离矩阵第c[j-1]列 vector<int> arrC2; // 距离矩阵第c[j]列 arrC1.resize(wstrPattern.size()+1); arrC2.resize(wstrPattern.size()+1); for(int i = 0; i <= wstrPattern.size(); i++) arrC1[i] = i; arrC2[0] = 0; int nMinStep = (std::numeric_limits<int>::max) (); int nMatchpos; for (int i = 1; i <= wstrText.size(); i++) { for(int j = 1; j <= wstrPattern.size(); j++) { arrC2[j] = arrC1[j-1] + (wstrText[i-1] == wstrPattern[j-1] ? 0 : 1); if (arrC2[j] > arrC1[j] + 1) arrC2[j] = arrC1[j] + 1; if (arrC2[j] > arrC2[j-1] + 1) arrC2[j] = arrC2[j-1] + 1; } for(int j = 1; j <= wstrPattern.size(); j++) arrC1[j] = arrC2[j]; if (nMinStep >= arrC2[wstrPattern.size()]) // 取最后一个最近似的子串 { nMinStep = arrC2[wstrPattern.size()]; nMatchpos = i; } } return nMatchpos - wstrPattern.size(); }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值