Getting Started with KMP algorithms

Source: Internet
Author: User

Learn a look at the pornography algorithm I think I can get better.

Obviously yesterday's question I all know how to imitate, but still will not change KMP, is I learn ugly

KMP is a linear time string matching algorithm designed by Knuth-morris-pratt three people

An introduction to the NXT array, horizontal slot, direct find too cool

Is that I can fall back when I match, because of the limited ability of the character

For example, Aaaaaaaaab and Aaaab to match, Aaaab is a pattern string, Aaaaaaaaab is a matching string, I do not have to back so many times, because in time to push down on the good

I'm a part of the match and I can go back to a certain position.

Here is a demo

I used to ask for the prefix function

void Pre (char *p) {    int  i,m,j;    M=strlen (p);    nex[0]=nex[1]=0;      for (int i=1; i<m; i++)    {        J=nex[i];          while (J&&p[i]!=p[j]) j=nex[j];        Nex[i+1]=p[i]==p[j]?j+1:0;    }}

Aaaab

0 0 1) 2 3

Aba

0 0 0

Pseudo code

Kmp-matcher (T,P) 1Nlength[T] 2mlength[P] 3Pi←compute-prefix-function (P) 4Q ←0? Number of characters matched. 5 for I ←1 to N ? Scan the text from left to right. 6 Do While Q > 0 andP[Q+ 1]≠T[I] 7 Do Q ←π[q ] if  p  [q  + 1] = t  [i ] 9 then  q q  + 1 if  q  = m  p  matched?11 then  print "Pattern occurs with Shift" i -m  q  ←π[q ]         
Compute-prefix-function (P) 1mlength[P] 2Π[1]←0 3k ←0 4 for Q ←2 to  m  5 do whi Le  k  > 0 and p  [k  + 1] ≠p  [q ] 6 do  k  ←π[k ] 7 if  p  [k  + 1] = EM class= "emphasis" >p  [q ] 8 then   K k  + 1 9 π[q  ] ←k  return  π         

Getting started with the KMP algorithm

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.