[Hihocoder] KMP algorithm

Source: Internet
Author: User

Each time we find a match, increase the global counter by 1.

For KMP, algorithm, your may refer to the following links which has nice explanations.

    1. KMP on Jboxer ' s blog;
    2. KMP on Geeksforgeeks, with a well-commented C code.
1#include <iostream>2#include <string>3#include <vector>4 5 using namespacestd;6 7vector<int> kmpprocess (stringt) {8     intn =t.length ();9vector<int> LPs (N,0);Ten      for(inti =1, Len =0; I <N;) { One         if(T[i] = =T[len]) Alps[i++] = + +Len; -         Else if(len) len = Lps[len-1]; -         Elselps[i++] =0; the     } -     returnLPs; - } -  + intKmpstringSstringt) { -     intm = s.length (), n = t.length (), CNTs =0; +vector<int> lps =kmpprocess (t); A      for(inti =0, j =0; I <m;) { at         if(S[i] = =T[j]) { -i++; -J + +; -         } -         if(j = = N) cnts++; -         if(I < m && S[i]! =T[j]) { in             if(j) J = lps[j-1]; -             Elsei++; to         } +     } -     returnCNTs; the } *  $ intMainvoid) {Panax Notoginseng     intcases; -scanf"%d", &cases); the      for(inti =0; i < cases; i++) { +         strings, t; ACIN >>T; theCIN >>s; +printf"%d\n", KMP (S, t)); -     } $     return 0; $}

[Hihocoder] 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.