KMP algorithm-C language Program implementation

Source: Internet
Author: User

Principle Reference ACM Algorithm Training tutorial Book
*KMP algorithm */#include <stdio.h> #include <string.h># Include<iostream>using namespace Std;void getNext (char a[],int next[]) {int i,j;next[1] = 0;j = 0;i = 2;int m = Strle N (a)-1; Starting from a[1] while (i<=m) {if (a[j+1] = = A[i]) {j + +; next[i++] = j;} else if (j==0) {next[i++] = 0;} else if (j>0) {j = next[j];}}} int match (char A[],char b[],int next[]) {int i=0,j=0;int pos;int n = strlen (a) -1;int m = strlen (b) -1;while (1) {if (i>n) {p OS =-1; break;} if (j==m) {//pos = i-j+1; break;cout<<i-j+1<< "" <<endl; J=NEXT[J];} if (b[j+1] = = A[i+1]) {j + +; i++;} Else{if (j==0) I++;else if (j>0) {j = next[j];}}} /* int main () {//char b[] = "!ABABBC"; char b[] = "!abab"; int l = strlen (b); int *next = new Int[l-1];getnext (b,next); int i ; for (i=1;i<=l-1;i++) {printf ("%d", Next[i]);} Cout<<endl;char a[] = "!ABABABABBC"; int pos = match (a,b,next); Cout<<endl<<pos<<endl;} *////////////////////////////////////////////////////*KMP application: Find the substring length of all prefixes equal to suffix in a string */void output (int i,int next[]) {while (next[i]>0) {cout<<next[i]<< ""; Next[i];}} /*int Main () {char b[] = "!ababa"; int l = strlen (b); int *next = new Int[l-1];getnext (b,next); int i;for (i=1;i<=l-1;i++) { printf ("%d", Next[i]);} Cout<<endl;output (L-1,next);d elete[] next; */

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

KMP algorithm-C language Program implementation

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.