KMP algorithm Java implementation strategy mode __ algorithm

Source: Internet
Author: User
KMP algorithm is a classic algorithm, online many great gods have given a very detailed description, this no longer repeat.

The following is the implementation of the KMP algorithm, which uses a policy pattern.


Public interface Inextbuilder {public
	abstract int[] Build (char[] p);

Implementation of recursive thought of writing Inextbuilder interface

Package COM.SOFT.KMP;

public class Recurnextbuilder implements Inextbuilder  {
	@Override public
	int[] Build (char[] p) {
		int[] Next=new Int[p.length];
		int k=-1;
		Next[0]=-1;
		Traversal 0->p.length-1 for
		(int i=0;i<p.length-1;i++) {
			if k==-1| | P[i]==p[k]) {
				k++;
				next[i+1]=k;
			} else{
				k=next[k];
			}
		return next;
	}

Non-recursive implementation of writing Inextbuilder interface

Package COM.SOFT.KMP;

public class Straitnextbuilder implements Inextbuilder {

	@Override public
	int[] Build (char[) p) {
		// Do it yourself, measure your level return
		null;
	}

Finally, write KMP class and test

Package COM.SOFT.KMP;

public class KMP {
	private inextbuilder nextbuilder;
	Public KMP (Inextbuilder nextbuilder) {
		this.nextbuilder=nextbuilder;
	}
        Public KMP () {
		this.nextbuilder=new recurnextbuilder ();
	}
	public int Kmpmatch (String s,string p) {
		char[] Pa=p.tochararray ();
		Char[] Sa=s.tochararray ();
    	Int[] Next=this.nextbuilder.build (PA);
    	for (int i=0,j=0;i<sa.length;) {
    	     if (J==-1 | | Sa[i]==pa[j]) {
    	    	 i++;j++;
    	     } else{
    	    	 j=next[j];
    	     }
    	     if (j==pa.length) {return
    	    	 i-j
    	     }}
    	return-1; 
    }
    public static void Main (string[] args) {
    	KMP kmp=new KMP ();
    	System.out.println (KMP. Kmpmatch ("Helllo", "Llo"));
    	
	}


Run Result: 3

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.