字符串的查找--KMP算法
来源:互联网 发布:单页源码 编辑:程序博客网 时间:2024/06/10 21:00
#include<iostream>
#include<string>
using namespace std;
int i = 0, j = -1;
int* next = new int[s.size()];
next[0] = -1;
while (i < s.length() - 1)
{
if (j == -1 || s[i]==s[j])
{
i++;
j++;
next[i] = j;
}
else
{
j = next[j];
}
}
return next;
}
int kmp_index(string &Tag, string& Ptn, int pos)
{
int* next = get_next(Ptn);
int i = pos;
int j = 0;
int Tlen = Tag.size();
int Plen = Ptn.size();
while (i < Tlen && j < Plen)
{
if (j == -1 || Tag[i] == Ptn[j])
{
i++;
j++;
}
else
{
j = next[j];
}
}
if (j >= Plen)
return i - Plen;
else
return -1;
}
//测试程序:
int main()
{
char ch;
do{
string Tag, Ptn;
int pos;
cout << "输入主串:";
cin >> Tag;
cout << "输入子串:";
cin >> Ptn;
cout << "输入主串中开始进行匹配的位置(首字符位置为0):";
cin >> pos;
int result = kmp_index(Tag, Ptn, pos);
if (result != -1)
cout << "主串与子串在主串的第" << result << "个字符(首字符的位置为0)处首次匹配" << endl;
else
cout << "无匹配子串" << endl;
cout << "是否继续测试(输入y或Y继续,任意其他键结束):";
cin >> ch;
} while (ch == 'y' || ch == 'Y');
return 0;
}
#include<string>
using namespace std;
int* get_next(string& s)
{int i = 0, j = -1;
int* next = new int[s.size()];
next[0] = -1;
while (i < s.length() - 1)
{
if (j == -1 || s[i]==s[j])
{
i++;
j++;
next[i] = j;
}
else
{
j = next[j];
}
}
return next;
}
int kmp_index(string &Tag, string& Ptn, int pos)
{
int* next = get_next(Ptn);
int i = pos;
int j = 0;
int Tlen = Tag.size();
int Plen = Ptn.size();
while (i < Tlen && j < Plen)
{
if (j == -1 || Tag[i] == Ptn[j])
{
i++;
j++;
}
else
{
j = next[j];
}
}
if (j >= Plen)
return i - Plen;
else
return -1;
}
//测试程序:
int main()
{
char ch;
do{
string Tag, Ptn;
int pos;
cout << "输入主串:";
cin >> Tag;
cout << "输入子串:";
cin >> Ptn;
cout << "输入主串中开始进行匹配的位置(首字符位置为0):";
cin >> pos;
int result = kmp_index(Tag, Ptn, pos);
if (result != -1)
cout << "主串与子串在主串的第" << result << "个字符(首字符的位置为0)处首次匹配" << endl;
else
cout << "无匹配子串" << endl;
cout << "是否继续测试(输入y或Y继续,任意其他键结束):";
cin >> ch;
} while (ch == 'y' || ch == 'Y');
return 0;
}
0 0
- 字符串的查找--KMP算法
- KMP算法查找字符串
- KMP字符串查找算法
- KMP字符串查找算法
- 字符串查找算法-KMP
- KMP - 字符串查找算法
- 字符串查找算法kmp
- 字符串查找算法kmp
- KMP字符串查找算法
- KMP字符串查找算法
- KMP 算法并非字符串查找的优化
- KMP 算法并非字符串查找的优化
- 字符串的查找:朴素查找算法和KMP算法
- 查找字符串之 KMP算法
- KMP子字符串查找算法
- 字符串查找(2)KMP算法
- 字符串匹配查找算法-KMP
- KMP算法:查找子字符串
- 编程之美-队列中取最大值操作问题
- 同构树的判别
- hdu 3037
- java list三种遍历方法性能比较
- sql server的查询操作练习(知识点)
- 字符串的查找--KMP算法
- 信号的概念
- 假设有一个字符串aabcad,请写一段程序,去掉字符串中不相邻的重复字符串,即上述字符串处理之后的输出结果为:aabcd
- linux文件权限与目录配置
- angular下拉列表
- 黑马程序员——基础知识——继承
- hdu 1114 Piggy-Bank
- 嵌入式系统安全复习(一)
- Java内部类提供的闭包功能,比指针更灵活更安全