[Data structure and algorithm] string matching KMP Algorithm

Source: Internet
Author: User

First, you need to understand the BF brute force matching algorithm. This algorithm sets a pointer for each string, and then the two pointers are moved back at the same time. If there is any mismatch,The primary string pointer returns to the next position before the start and backward shift, and the pattern string pointer returns to the beginning..

To compare the KMP algorithm, we also set two pointers, and then the two pointers are moved back at the same time. If the two pointers do not match,The master string pointer remains unchanged, and the mode string pointer traces back to a certain distance.. The number of pattern string pointers Backtracking is hard to understand for the first time when you look at the KMP algorithm. In fact, think carefully,The prefix and suffix of the pattern string are actually being matched. When P [k]! = P [J] is a mismatch, so the prefix pointer needs to be traced back, so the last K = next [k].

    • Code Implementation

/*** Source code name: KMP. java * Date: 2014-09-03 * program function: KMP algorithm * copyright: [email protected] * a2bgeek */public class KMP {public int [] getnext (string in) {int [] Next = new int [in. length ()]; Int J = 0; int K =-1; next [J] = K; while (j <next. length-1) {If (k =-1 | in. charat (K) = in. charat (j) {J ++; k ++; next [J] = K;} else {k = next [k] ;}} for (int I: Next) {system. out. print (I + "");} system. out. println (); return next;} public int KMP (string S, string p) {int I = 0; Int J = 0; int [] Next = getnext (P ); while (I <S. length () & J <p. length () {If (j =-1 | S. charat (I) = P. charat (j) {I ++; j ++;} else {J = next [J] ;}} if (j = P. length () {return 1 ;}else {return-1 ;}} public static void main (string [] ARGs) {KMP = new KMP (); string S = "acbfdfjkdhg"; string P = "dfdj"; system. out. println (KMP. KMP (S, P ));}}


[Data structure and algorithm] string matching 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.