KMP算法

KMP匹配算法对我来说很复杂。

目前只是有一些了解。
                                 2013.6.10


KMP算法远没有想象中那么难。
要理解KMP算法,只需要理解这个就行了。以abaabcac为例


j           1 2 3 4 5 6 7 8
--------------------------
模式串  a b a a b c a c
next[j]   0 1 1 2 2 3 1 2


设next[j] = k, 这表明在模式串中存在下列关系
  'p1......pk-1'   =   'pj-k+1.......pj-1'
  
  void get_next(SString T, int next[]){
        i = 1;     next[1] = 0;     j = 0;
        while (i < T[0]) {
             if(j == 0||T[i] == T[j]) { ++i; ++j; next[i] = j;}
             else j = next[j];
        }
  }
  
                               2013.7.3


#include <iostream>  
  
  
static const int MaxSize = 100;  
  
  
using namespace std;  
  
  
void GenKMPNext (int Next[], char C_My_String[] , int len_mystring)  
{  
    int i = 0, j = -1;  
  
  
    Next[0] = -1;  
    while (i < len_mystring)  
    {  
        while(j >= 0 && C_My_String[i] != C_My_String[j])  
            j = Next[j];  
        i++; j++;  
        if(C_My_String[i] == C_My_String[j])  
            Next[i] = Next[j];  
        else Next[i] = j;  
    }  
}  
  
  
int Find (char C_String[], char My_String[]  ,int len_of_string, int len_of_mystring )  
{  
    int i, j, next[MaxSize];  
    GenKMPNext(next, My_String, len_of_mystring);  
    for(i = 0,j = 0; i < len_of_mystring && j < len_of_string;)  
    {  
        if(My_String[i] == C_String[j])  
        {i++; j++;}  
        else if (next[i] >= 0)  
            i = next[i];  
        else   
        {i = 0; j++;}  
    }  
    if (i >= len_of_mystring)  
        return j - len_of_mystring;  
    else  
        return -1;  
}  
  
  
void main()  
{  
    char String[MaxSize];  
    char MyString [MaxSize];  
    int next[MaxSize];  
    int string_length;                 //储存字符串长度  
    int my_string_length;              //储存子串长度  
    cout << "请输入子串" << endl;  
    scanf ("%s", &*MyString);  
    cout << "请输入字符串" << endl;  
    scanf ("%s", &*String);  
    for( string_length = 0; String[string_length] !='\0'; string_length ++)  
        ;                                        //string_length 储存字符串长度  
    for( my_string_length = 0; MyString[my_string_length] !='\0'; my_string_length ++)  
        ;                                         //my_string_length 储存zi串长度  
    int where = Find (String, MyString, string_length, my_string_length);  
    cout << where+1 << endl;  
}  


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值