KMP algorithm implemented in Java

Source: Internet
Author: User

/** <Br/> */<br/> package COM. baseframework; </P> <p>/** <br/> * @ author sunyanan KMP <SPAN class = 'wp _ keywordlink '> algorithm </span> <br/> * <br/> */<br/> public class kmpalgorithm {</P> <p>/** <br/> * Next function of the computing mode string <br/> * <br/> * @ Param desstr <br/> * mode string <br/> * @ return mode string's next function, use arrays to save <br/> */<br/> Private Static int [] kmpnext (string desstr) {<br/> int Len = desstr. length (); <br/> int I = 0; <br/> I Nt j =-1; <br/> int next [] = new int [Len]; <br/> while (I <len-1) {<br/> If (j =-1 | (desstr. charat (I) = (desstr. charat (j) {<br/> I ++; <br/> J ++; <br/> If (desstr. charat (I )! = (Desstr. charat (j) {<br/> next [I] = (J + 1 ); <br/>} else {<br/> next [I] = next [J]; <br/>}< br/>} else {<br/> J = (next [J]-1 ); <br/>}< br/> return next; </P> <p >}</P> <p>/** <br/> * KMP core algorithm <br/> * @ Param sourcestr <br/> * @ Param desstr <br/> * @ Param POS <br/> * returns if @ return is successful and matches the first character of the master string. <br/> * location, -1 is returned if a failure occurs. The index starts from 0 <br/> */<br/> Public static int index (string sourcestr, string desstr, int POS) {<br/> int next [] = kmpnext (desstr); <br/> int I = 0; <br/> Int J = 0; <br/> while (I <sourcestr. length ()-1 & J <desstr. length ()-1) {<br/> If (j = 0 | (sourcestr. charat (I) = desstr. charat (j) {<br/> I ++; <br/> J ++; <br/>} else <br/> J = (next [J]-1); <br/>}< br/> If (j> desstr. length ()-2) {<br/> return (I-desstr. length () + 1); <br/>}else <br/> return-1; </P> <p >}< br/>

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.