Implementation of the kmp algorithm for string search (Java version)

Source: Internet
Author: User

Just now I saw an article on the news channel: Ruan Yifeng: String-matching KMP algorithm, which is illustrated in plain text and easy to understand. It was implemented in Java.

For those who only sort algorithms, it is also a difficult task.

The logic written last time has a problem. I don't know if there are any bugs this time.

1/** 2 * knuth-Morris-Pratt algorithm 3*4 * @ author yinqi 5 * @ date 2013-5-5-11:11:56 am 6 */7 public class stringsearchkmp {8 9 /** 10 * @ Param args11 */12 public static void main (string [] ARGs) {13 int Index = knuthmorrispratt ("abcdabcdaabcdabcabcdabdabd", 14 "abcdabdabd", 0); 15 system. out. println (INDEX); 16} 17 18/** 19 * string search kmp algorithm <br> 20*21 * @ Param searchstr22 * @ Param matchstr23 * @ Param sta Rt24 * @ return25 */26 public static int knuthmorrispratt (string searchstr, string matchstr, 27 int start) {28 char [] searchchar = searchstr. tochararray (); 29 char [] mchar = matchstr. tochararray (); 30 int [] fixnum = lengthkmp (mchar); 31 system. out. println (arrays. tostring (fixnum); 32 int neglect = 1; 33 for (INT I = start; I <= searchchar. length-mchar. length; I + = neglect) {34 Boolean con = true; 35 (Int J = 0; j <mchar. length; j ++) {36 IF (searchchar [I + J]! = Mchar [J]) {37 con = false; 38 neglect = J + 1-fixnum [J = 0? 0: J-1]; 39 break; 40} 41} 42 if (CON) {43 return I + 1; 44} 45} 46 Return-1; 47} 48 49/** 50 * Get the length of a common element of some matching values <br> 51*52 * @ Param mchar53 * @ return54 */55 public static int [] lengthkmp (char [] mchar) {56 int [] fixnum = new int [mchar. length]; 57 for (INT I = 1, j = 0; I <mchar. length; I ++) {58 If (mchar [J] = mchar [I]) {59 fixnum [I] = J + 1; 60 J ++; 61} else if (j> 0) {62 J = 0; 63 I-= J; 64} 65} 66 // return [0, 0, 0, 0, 1, 2, 0, 1, 2, 0] abcdabdabd67 return fixnum; 68} 69} 70/* 71 * A bc72 * AB c73 * A bcd74 * AB cd75 * ABC d76 * A bcde77 * AB cde78 * ABC de79 * ABCD E 80 */

 

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.