KMP algorithm C Code Description

Source: Internet
Author: User

/*

* Prepared by junyisun @ CCNU

* E-MAIL: CCNUSJY@GMAIL.COM

* KMP algorithm C Code Description

*/

 

# Include <stdio. h>

# Include <string. h>

# Include <stdlib. h>

# Define max_s 101/* Maximum length of the master string is 100 */

# Define max_p 21/* the maximum length of the mode string is 20 */

 

Char s [max_s], p [max_p];/* s is the main string, and P is the mode string */

Int nextv [max_p];/* P nextv array */

 

Void init_nextv ()

{

Int I = 0, j =-1;

Int p_len;/* length of the mode string */

P_len = strlen (P );

Nextv [0] =-1;

While (I <p_len-1 ){

If (j =-1 | P [I] = P [J]) {

++ I; ++ J;

If (P [I]! = P [J]) nextv [I] = J;

Else nextv [I] = nextv [J];

}

Else J = nextv [J];

}

}

 

Int KMP ()

{

Int I = 0, j = 0, s_len, p_len;

S_len = strlen (s );

P_len = strlen (p );

While (I <s_len & j <p_len ){

If (j =-1 | s [I] = p [j]) {

I ++; j ++;

}

Else j = nextv [j];

}

If (j = p_len) return i-p_len;

Else return-1;

}

 

 

Int main ()

{

Int Index = 0;

Printf ("Enter the main string :");

Scanf ("% s", S );

Printf ("Enter the substring :");

Scanf ("% s", P );

Init_nextv ();

Index = KMP ();

If (index! =-1)

Printf ("matched successfully, matched position % d/N", index );

Else

Printf ("matching failed/N ");

System ("pause ");

Return 0;

}

 

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.