KMP Algorithm for Java implementation

Source: Internet
Author: User

 Packagedatastructure;Importjava.util.ArrayList;Importjava.util.List;//implementation of KMP algorithm//The following code is written in conjunction with the Freedom Data Public classDMPtest1 {Private intnext[]; PrivateString Target;//Main string    PrivateString pattern;//Sub-string    Char[] t;//Main string Character    Char[] p;//substring characters    Private StaticList<integer>list;  PublicDMPtest1 () {} PublicDMPtest1 (String pattern,string target) { This. Pattern =pattern;  This. target =Target; P= This. Pattern.tochararray (); T= This. Target.tochararray (); //list = new arraylist<integer> (); //Initializes a collection to hold the index of the matching substring in the main stringNext = This. Getnextarray ( This. pattern);//accept returned arrays that are already well-received            }         Public voidDisplaynext () {//Print Next Array         for(inti=0;i<next.length; i++) {System.out.print (next[i]); }            }         PublicList<integer>Gettargetindex () {List<Integer> list =NewArraylist<integer>(); intNum=0; inti = 0;//Main string Target subscript        intj = 0;//Sub-string pattern subscript        if(t.length>=p.length) { while(i<t.length) {//because the subscript of the main string is constant, only the match exceeds his own length and jumps out of the loop .                                if(p[j]==T[i]) {num++;//For the first time, then num clear 0.J + +; I++; //System.out.println ("a target has been found" +j+p.length);                        if(j>p.length-1) {//if it's the last number.List.add (i-J);//adds a matching string to the list in the main string position (index of the first character)J=0; //indicates that a substring has been matched//J is already equal to the next subscript of the last subscript of the P array.                        }                    }Else {                        //two characters don't match.//the new index of J is directly equal to NEXT[J] The conclusion is written on the paper .                                                if(num==0) {J=0; //the first time is unequal, then I need to self-addi++; //This structure should be careful, be sure to write in front of the next if!                         }                                            if(num>0) {                                                        //The description is not the first time inequality, then the main string subscript does not have to addj=Next[j]; Num=0; }                                                                    //System.out.println (j);                    }            }                                            }Else{System.out.println ("The pattern string must be greater than or equal to the main string!" "); }        returnlist; }            /*** 1, the method is used to return a next[] array, which holds the corresponding t{0~j-1} string of the pattern string (the longest prefix and the number of the same matching characters of the suffix) j is the subscript of the pattern String * 2, pattern is the mode string, to convert to char[] , if you want to search for freedom, it is necessary to convert the freedom to f,r,e,e,d,o,m char type array * * 3, this method is implemented with the idea of recursion, you can write the next array at a glance.     In the back will explain! *       */     Public int[] Getnextarray (String pattern) {intNext[] =New int[P.length]; next[0] = 1; intj = 0;//Next array subscript        intK =-1;//used to temporarily save the value of the next array//because the next array is designed to seek DMP, the entire next array is shifted to the right by 1, so the first bit is generally-1, which means there is no such string//and Next[1]=0, because the second position of the string to be t{0~j-1} prefix and suffix of the longest length of the same value, so 1 characters is an empty set, this will be implemented in the method body//when J assigned the last word, it jumps out of the loop, and if the string has 8 characters, then J must be less than 8-1         while(j<p.length-1) {            if(k==-1| | p[k]==P[j]) {                //If the match succeeds, the J,k two subscript is added to compare the next combination for equalityJ + +; K++; NEXT[J]=K; } Else {                //if it doesn't match, then J still doesn't move, K takes the value of the previous Kk = Next[k];//know K is 1 no match value returned 0            }        }        returnNext; }     Public Static voidMain (String args[]) {DMPtest1 dmp=NewDMPtest1 ("abc", "Afwefwaefaaaaabcawiefjawoijfeioawjofabc");//initialized for next array//Dmp.displaynext ();List = Dmp.gettargetindex ();//iterates through the matching main string and returns the index to the list         for(intI=0;i<list.size (); i++) {System.out.println ("The position of the string in the main string is" +List.get (i)); } System.out.println ("Total {" +list.size () + "} Matching Results"); }}

KMP Algorithm for 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.