String Matching (KMP) algorithm and Java implementation

Source: Internet
Author: User

first, what is the KMP algorithm?


Wikipedia's explanation is that in computer science, the Knuth-morris-pratt string lookup algorithm (referred to as the KMP algorithm) finds the occurrence of a word w within a main text string s. This algorithm, by applying a mismatch to the word itself, contains enough information to determine where the next match will begin, thus avoiding the re-checking of previously matched characters.


Prefixes and suffixes of strings


Prefix: string In addition to the last character of the entire head combination;

Suffix: A string that handles all combinations of headers for the first character;

Third, string partial match table


The essence of "partial match" is that sometimes the string header and tail are duplicated. For example, "Abcdab" has two "AB", then its "partial match value" is 2 ("ab" length). When the search term moves, the first "AB" Moves backwards 4 bits (the length of the string-part of the match), and it can come to the second "ab" position. So we need to find a matching value for each substring in a string, that is, to find a partial match value table for the string, so that we can jump based on the matching table in the following matching string, rather than having to move backward by one character, that's the key.

Iv. implementation process of KMP algorithm


To put it simply, the KMP algorithm is based on the partial match table we have obtained above: the substring should be moved back several when a character of the substring found in the matching process does not correspond to the string to be matched.

Number of bits moved = total length of the string that has been matched successfully-partial matching value of the successful string has been matched

Some around, for a chestnut, if I want to determine whether the string "BBC Abcdab Abcdabcdabde" contains string "ABCDABD", I call this long string to be matched string, the "Abcdabd" is called a substring (it may be wrong but understand the line).

The process of matching is:


Compares the first character of the string "BBC Abcdab Abcdabcdabde" with the first character of the search term "abcdabd". Because B does not match A, the search term moves one after the other. Until there is a matching character position, as follows:


When the match to D was found to be wrong, this time:

The string that has been matched successfully is: Abcdab

The total length of the string that has been successfully matched: 6

Partial match value for successfully matched string: 2

Number of positions to move = 6-2, move the substring backward 4 bits, continue to start matching

The same truth, at this time has matched the successful string is AB, moving the number of digits = 2-0, moving backward 2-bit continue to match




There is no successful string, move backward One

The string that has been successfully matched is: the partial match value of Abcdab,abcdab is 2, the number of bits moved = 6-2, and the 4 bits are moved backwards

At this point all the characters of the substring are matched and the search is complete.


V. Implementation of Java

public class kmpalgo {    //find the partial match value of the string to be matched, put it in the next array      Static void getnext (String pattern,int[] next) {         int j = 0;        int k = -1;         next[0] = -1;         int len = pattern.length ();         while (j  < len-1) {            if (k ==  -1 | |  pattern.charat (j)  == pattern.charat (j)) {                 j++;                 k++;                 next[j] = k;            } else{                k =  next[k];            }         }            }  &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;STATIC&NBSP;INT&NBSP;KMP (String s,string pattern) {         int i = 0;         int j = 0;        int slen =  S.length ();         int plen = pattern.length ();         int[] next = new int[plen];         GetNext (Pattern,next);         while (i < slen & & j < plen) {            if ( S.charat (i)  == pattern.charat (j)) {                 i++;                 j++;                             }else if (next[j ]&NBSP;==&NBSP;-1) {                 i++;                j  = 0;            }else{                 j = next[j];             }             if (J == plen) {                 return i-j;            }         }        return - 1;            }    /**      * @param      */    public static  void main (String[] args) {        string str  =  "ABCDABDEYGF";        string pat =  "ABCDABD";      &NBSP;&NBSP;&NBSP;//KMPALGO.KMP (Str, pat);         System.out.println (KMPALGO.KMP (Str, pat));     }}



























String Matching (KMP) algorithm and Java implementation

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.