关注
#include <iostream>
#include <string>
using namespace std;
int b_force_match(string str, string ptr)
{
int i, j, temc;
int tlen = ptr.length();
int plen = str.length();
for (i = 0, j = 0; i <= plen - tlen; i++)
{
temc = i;
j = 0;
while (str[temc] == ptr[j] && j < tlen)
{
temc++;
j++;
}
if (j == tlen)
return i;
}
return -1;
}
void clnext(string str, int *next)
{
int len=str.length();
next[0] = -1;
int k = -1;
for (int q = 1; q < len; q++)
{
while (k > -1 && str[k + 1] != str[q])
k = next[k];//回溯
if (str[k + 1] == str[q])
k++;
next[q] = k;
}
}
int KMP(string str,string ptr)
{
int slen=str.length();
int plen=ptr.length();
int *next = new int[plen];
clnext(ptr, next);
int k = -1;
for (int i = 0; i < slen; i++)
{
while (k >-1&& ptr[k + 1] != str[i])
k = next[k];
if (ptr[k + 1] == str[i])
k = k + 1;
if (k == plen-1)
{
delete next;
return i-plen+1;
}
}
delete next;
return -1;
}
int main()
{
string str = "ahraaahahafafderqhgadgdfghadfhnmym,,aryzkiababaabaftyacfabaou";
string ptr = "ababaabaf";
cout << "patternmatch" << endl;
cout << "b_force:" << endl;
cout << b_force_match(str, ptr) << endl;
cout<<"KMP:"<<endl;
cout << KMP(str, ptr) << endl;
return 0;
}
查看原帖
点赞 评论
相关推荐
点赞 评论 收藏
分享
09-24 10:27
焦作工贸职业学院 Java
我的offer呢😡:这不才9月吗,26到明年毕业前能一直找啊 点赞 评论 收藏
分享
牛客热帖
更多
正在热议
更多
# 月薪多少能在一线城市生存 #
74185次浏览 484人参与
# 技术转行的心路历程 #
72166次浏览 739人参与
# 百度秋招 #
32341次浏览 314人参与
# 互联网行业现在还值得去吗 #
37131次浏览 266人参与
# 虾皮开奖 #
43161次浏览 206人参与
# 你小时候最想从事什么职业 #
133075次浏览 1978人参与
# 落户对你的求职选择影响有多大 #
29535次浏览 101人参与
# 总结:哪家公司最喜欢泡池子 #
150316次浏览 542人参与
# 第一次找实习,我建议__ #
28493次浏览 356人参与
# 滴滴歧视残疾人HR被开除 #
23206次浏览 86人参与
# 从mentor身上学到了__ #
23958次浏览 413人参与
# 你怎么评价今年的春招? #
144395次浏览 1394人参与
# 你认为工作的意义是什么 #
208334次浏览 1339人参与
# 韶音科技求职进展汇总 #
62546次浏览 506人参与
# 小米编程考试 #
22626次浏览 143人参与
# 外出实习被同学举报 #
6695次浏览 39人参与
# 打工人的至爽时刻or至暗时刻 #
43194次浏览 224人参与
# 华为海思工作体验 #
36408次浏览 146人参与
# 除了主业以外,你还有哪些其他收入? #
36676次浏览 303人参与
# 在国企工作的人,躺平了吗? #
376369次浏览 3934人参与
# 运营每日一题 #
109530次浏览 880人参与
查看7道真题和解析