KMP Character matching algorithm

Source: Internet
Author: User

Last vacation to learn KMP, but basic not, so forget clean ... The core idea of this is next array, next array called longest same prefix suffix. It's a good algorithm, KMP.

The matching process is more than the original violence match a jump to jump to the next.

Here is a link: From beginning to end KMP, write very good, very understood!

Paste the Board code: (self-written comments, may not be, welcome to point out)

#include <cstdio>#include<cmath>#include<cstring>using namespacestd;intnext[1000005];Chars[1000005];//S is a matching stringChart[1000005];//T is a text stringintans[1000005];//Record AnswersintMain () {scanf ("%s%s", T +1, S +1);//starting from 1 to save    intls = strlen (s +1); intlt = strlen (t +1); intK =0;//k is the maximum number of suffixes to matchnext[1] =0;  for(inti =2; I <= ls;i++)//start matching S, build next array    {         while(k! =0&&s[i]! = s[k +1])//suffix is not equal then return to Next[k]K =Next[k]; if(S[i] = = S[k +1]) k++;//suffix equalNext[i] =K; } k=0; intnum =0;  for(inti =1; I <= lt;i++)//start matching text string    {         while(k! =0&&t[i]! = s[k +1]) K=Next[k]; if(T[i] = = S[k +1]) k++; if(k = = ls)//if the text string is already matched to S, record the answer{num++; Ans[num]= I-ls +1; }    }     for(inti =1; I <= num;i++) printf ("%d\n", Ans[i]);  for(inti =1; I <= ls;i++) printf ("%d", Next[i]);//Output Answer    return 0;}

KMP Character matching 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.