Implementation of KMP algorithm in C Language

Source: Internet
Author: User

I still don't understand the KMP algorithm, so I have to say this is an awesome algorithm.

Put it here for later viewing

Int Index_KMP (const char * str, const char * t)

{
Int str_size = strlen (str );
Int t_size = strlen (t );

Int * next = new int [t_size];
GetNext (t, next, t_size );
Int I = 0, j = 0;
While (I <str_size & j <t_size)
{
If (j =-1 | str [I] = t [j])
{
++ J;
++ I;
}
Else j = next [j];
}
If (j = t_size)
{
Return I-j;
}
Else return-1;

}


Void GetNext (const char * t, int * & next, int size)
{
Int I = 0, j =-1;
Next [0] =-1;
While (I <size)
{
If (j =-1 | t [I] = t [j])
{
++ I;
++ J;
If (t [I]! = T [j])
{
Next [I] = j;
}
Else next [I] = next [j];
}
Else j = next [j];
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.