Skip to content

Instantly share code, notes, and snippets.

@shonenada
Created December 12, 2012 10:50
Show Gist options
  • Save shonenada/4266864 to your computer and use it in GitHub Desktop.
Save shonenada/4266864 to your computer and use it in GitHub Desktop.
kmp in java
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