C++实现KMP模式匹配算法
2015-08-20 23:22
465 查看
#include<iostream>
#include<string>
#include<vector>
using namespace std;
void Next(const string & pat,vector<int> & next)
{
next.resize(pat.length());
if(pat.length() == 0)
return;
next[0] = -1;
for(size_t pos = 1; pos < pat.length(); ++pos)
{
size_t sublen = pos-1;
while(sublen >= 0)
{
if(pat.substr(0, sublen) == pat.substr(pos-sublen+1, sublen))
break;
--sublen;
}
next[pos] = sublen;
}
return;
}
int main(void)
{
string str1, str2;
while(cin >> str1 >> str2) {
vector<int> next;
Next(str2, next);
vector<int> pos;
int i = 0, j1 = 0, j2 = 0;
while(j1 < str1.length())
{
j2 = j1 - i;
if(j2 >= str2.length()) {
// found
pos.push_back(i);
// move on;
int delta = str2.length();
i = i + delta;
j1 = max(i,j1);
}
else if(str1[j1] == str2[j2]) {
++j1;
}
else { // str1[j1] != str2[j2];
int delta = j2 - next[j2];
i = i + delta;
j1 = max(i,j1);
}
}
//output.
cout << "str1.length(): " << str1.length() << endl;
cout << "str2.length(): " << str2.length() << endl;
cout << "str1 from pos: " << endl;
for(int i = 0; i < pos.size(); ++i)
cout << "[" << (i+1) << "]: " << str1.substr(pos[i], string::npos) << endl;
cout << "str2: " << str2 << endl;
}
return 0;
}
参考自: http://www.cnblogs.com/BeyondAnyTime/archive/2012/07/09/2583133.html
#include<string>
#include<vector>
using namespace std;
void Next(const string & pat,vector<int> & next)
{
next.resize(pat.length());
if(pat.length() == 0)
return;
next[0] = -1;
for(size_t pos = 1; pos < pat.length(); ++pos)
{
size_t sublen = pos-1;
while(sublen >= 0)
{
if(pat.substr(0, sublen) == pat.substr(pos-sublen+1, sublen))
break;
--sublen;
}
next[pos] = sublen;
}
return;
}
int main(void)
{
string str1, str2;
while(cin >> str1 >> str2) {
vector<int> next;
Next(str2, next);
vector<int> pos;
int i = 0, j1 = 0, j2 = 0;
while(j1 < str1.length())
{
j2 = j1 - i;
if(j2 >= str2.length()) {
// found
pos.push_back(i);
// move on;
int delta = str2.length();
i = i + delta;
j1 = max(i,j1);
}
else if(str1[j1] == str2[j2]) {
++j1;
}
else { // str1[j1] != str2[j2];
int delta = j2 - next[j2];
i = i + delta;
j1 = max(i,j1);
}
}
//output.
cout << "str1.length(): " << str1.length() << endl;
cout << "str2.length(): " << str2.length() << endl;
cout << "str1 from pos: " << endl;
for(int i = 0; i < pos.size(); ++i)
cout << "[" << (i+1) << "]: " << str1.substr(pos[i], string::npos) << endl;
cout << "str2: " << str2 << endl;
}
return 0;
}
参考自: http://www.cnblogs.com/BeyondAnyTime/archive/2012/07/09/2583133.html
相关文章推荐
- C++ 小技巧之一条语句多行书写
- Codeforces Round #285(Div.2) A,B,C 解题报告
- C++ 的忠告
- 04==C语言(分支结构)
- C++ 小技巧之 字符串字面值拼接
- C++嵌入Python程序(二):参数传入及返回
- C++对象模型——异常处理 (Exception Handling)(第七章)
- 传送门2号 - 算法 x C++
- 警惕C++隐式转换(More Effectiv C++_5(运算符))
- 迷宫游戏C语言实现
- C++中引用(&)的用法和应用实例(转)
- C/C++笔试面试系列之一
- C#与C++的命名空间
- 零基础学C语言 笔记一 变量 printf
- 从背后知道C语言程序是怎么运行的
- C++头文件与实现文件分别写什么
- C语言-函数
- C++ string学习(转)
- C++之程序时间统计类实现
- 二叉树的C++实现代码