关于串的模式匹配的next值如何计算

lenient315 2009-05-30 11:25:13
我是按照严文敏的教材看的,就是计算next[j]
就是想问下下面这个这么算
j :1 2 3 4 5 6 7 8
T :a b a a b c a c
next值的答案为0 1 1 2 2 3 1 2
next[1]=0
next[2]=1
这两个是规定的
接下来的是如何计算的呢?

望指点迷津 希望有详细的过程

PS.我也发现论坛有人问个一样的问题 但是看了 感觉解答不是特别详细 还是没有解我心头之惑,所以希望回帖的时候能尽量说的详细一点,非常感谢
...全文
1164 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复

#include <vector>
#include <string>
#include <iostream>
using namespace std;
const vector<int> * kmp_next(string &m) // count the longest prefex string ;
{
static vector<int> next(m.size());
next[0]=0; // the initialization of the next[0];

int temp; // the key iterator......

for(int i=1;i<next.size();i++)
{
temp=next[i-1];

while(m[i]!=m[temp]&&temp>0)
{ temp=next[temp-1];
}

if(m[i]==m[temp])
next[i]=temp+1;
else next[i]=0;


}

return &next;

}


bool kmp_search(string text,string m,int &pos)
{
const vector<int> * next=kmp_next(m);

int tp=0;
int mp=0; // text pointer and match string pointer;

for(tp=0;tp<text.size();tp++)
{
while(text[tp]!=m[mp]&&mp)
mp=(*next)[mp-1];

if(text[tp]==m[mp])
mp++;

if(mp==m.size())
{ pos=tp-mp+1;
return true;
}
}

if(tp==text.size())
return false;
}

int main()
{
int pos=0;
kmp_search("abcacbc","ac",pos);
cout<<"position = "<<pos+1<<endl;
return 0;
}











PS:代码来自互联网
lenient315 2009-05-31
  • 打赏
  • 举报
回复
关于KMP不同的书定义也不一样
今天下午又仔细看了下严的书 感觉是会算了 但是刚又找了几道题试试 但是算的跟答案由不一致 - -#
liao05050075 2009-05-31
  • 打赏
  • 举报
回复
KMP算法详解
http://www.matrix67.com/blog/archives/115
写得是比较通俗易懂

33,008

社区成员

发帖
与我相关
我的任务
社区描述
数据结构与算法相关内容讨论专区
社区管理员
  • 数据结构与算法社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧