Created
December 12, 2012 10:50
-
-
Save shonenada/4266864 to your computer and use it in GitHub Desktop.
kmp in java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package Notepad; | |
public class KMP { | |
static int[] getNext(String p){ | |
int i=1,j=0; | |
int[] next = new int[p.length()+2]; | |
char[] pattern = p.toCharArray(); | |
next[0] = -1; | |
next[1] = 0; | |
while(i<p.length()-1){ | |
if(pattern[i] == pattern[j]){ | |
i++; | |
j++; | |
next[i] = next[j]; | |
} | |
else if(j == 0){ | |
next[i+1] = 0; | |
i++; | |
} | |
else{ | |
j = next[j]; | |
} | |
} | |
return next; | |
} | |
static int findKMPSub(String str, String p,int start, int next[]){ | |
char[] string = str.toCharArray(); | |
char[] pattern = p.toCharArray(); | |
int i = start; | |
int j=0,v; | |
while(i<str.length() && j<p.length()){ | |
if(j == -1 || string[i] == pattern[j]){ | |
i++; | |
j++; | |
} | |
else{ | |
j = next[j]; | |
} | |
} | |
if ( j == p.length()){ | |
v = i - p.length(); | |
}else{ | |
v = -1; | |
} | |
return v; | |
} | |
static int findSub(String str, String p, int start){ | |
int m = p.length(); | |
int[] next = new int[m]; | |
next = getNext(p); | |
int v = findKMPSub(str,p,start,next); | |
return v; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment