String KMP Algorithm

Source: Internet
Author: User

# Include <iostream>

 

Using namespace STD;

 

Void fail (string & S, int f []);

Int fastfind (string & SRC, string & Pat, int * fail );

 

/*

Fail [I] = K (0 <= k <I and meet p [0] P [1]… P [k] = P [I-K] P [I-k + 1]… The maximum integer of P [I)

=-1 (Others)

*/

 

Void fail (string & S, int f [])

{

Int lengthp = S. Length ();

F [0] =-1;

For (Int J = 1; j <lengthp; j ++)

{

Int I = f [J-1]; // previous value

 

While (s [J]! = S [I + 1] & I>-1)

{

I = f [I];

}

 

If (s [J] = s [I + 1])

F [J] = I + 1;

Else

F [J] =-1;

}

Cout <Endl;

}

 

Int fastfind (string & SRC, string & Pat, int * fail)

{

Int posp = 0, post = 0;

Int lengthp = Pat. Length (), lengtht = SRC. Length ();

While (posp <lengthp & post <lengtht)

{

If (Pat. At (posp) = SRC. At (post ))

{

Posp ++;

Post ++; // If the match is successful, one digit is moved back at the same time.

}

Else if (posp = 0)

{

Post ++; // if the first character does not match, the matched string is removed to the backend.

}

Else

{

Posp = fail [posP-1] + 1; // otherwise, the starting position of the rematching is found through the invalidation Function

}

}

 

If (posp <lengthp)

{

Return-1; // not found

}

Else

{

Return post-lengthp; // return the starting position of the matched string when the matching is successful.

}

}

 

Int main (void)

{

String src = "aabbaabcaabb ";

String T = "AABC ";

Int A [20];

Fail (t, );

Int Pos = fastfind (SRC, T, );

Cout <"Pos =" <POS <Endl;

 

For (int K = 0; k <t. Length (); ++ K)

{

Cout <k <":" <A [k] <Endl;

}

}

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.