正文

练习:KMP算法 字符串匹配2006-05-08 00:16:00

【评论】 【打印】 【字体: 】 本文链接:http://blog.pfan.cn/bclz/13689.html

分享到:

////字符串模式匹配:KMP算法////06.05.07 vc6.0调试通过//ZYQ//#include <iostream.h>#include <string>int* get_next(char *T);void main(){    char* s="hhhsauhduwdh";    char* t="hdu";    int i=0;    int j=0;    int S=strlen(s);    int T=strlen(t);    int *next=get_next(t);    while(i<S&&j<T)    {//判定条件i<S&&j<T说明:字符串数组下标从0开始,到字符串长度减1结束        if(j==0||s[i]==t[j])        {i++;j++;}//继续向后比较字符        else            j=next[j];//模式串向后移动    }    if(j>=T)        cout<<i-T+1<<endl;//匹配成功    else        cout<<"0"<<endl;//匹配失败}//KMP算法克服了主串中i指针的回朔问题//求next值的算法//06.05.07 get_next函数调试时仍有问题。编译时通过,运行时出错。//int* get_next(char *T){//返回指向next数组首地址的指针    int i=1;    int next[100];    next[1]=0;    int j=0;    while(i<strlen(T))    {        if(j==0||T[i]==T[j])        {i++;j++;next[i]=j;}        else j=next[j];    }//while    return next;}//get_next

阅读(5058) | 评论(3)


版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!

评论

loading...
您需要登录后才能评论,请 登录 或者 注册