Skip to content

Instantly share code, notes, and snippets.

@liuxinglanyue
Created June 16, 2015 15:46
Show Gist options
  • Save liuxinglanyue/82c1fdae747a90c79305 to your computer and use it in GitHub Desktop.
Save liuxinglanyue/82c1fdae747a90c79305 to your computer and use it in GitHub Desktop.
KMP算法,查找子串
public class KMP {
public static void main(String[] args) {
String source = "ababababcaab";
String target = "abababca";
KMP kmp = new KMP();
int[] result = kmp.preProcess(target);
for(int i=0; i<result.length; i++) {
System.out.println(result[i]);
}
System.out.println(kmp.kmp(source, target));
}
public boolean kmp(String source, String target) {
int sourceLen = source.length();
int targetLen = target.length();
int[] next = preProcess(target);
int j = 0;
for(int i=0; i<sourceLen; i++) {
while(j != 0 && source.charAt(i) != target.charAt(j)) {
j = next[j - 1];
}
if(source.charAt(i) == target.charAt(j) ) {
j++;
}
if(j == targetLen) {
//if find all
//j = next[j-1];
return true;
}
}
return false;
}
public int[] preProcess(String s) {
int size = s.length();
int[] next = new int[size];
next[0] = 0;
int j = 0;
for(int i=1; i<size; i++) {
while(j != 0 && s.charAt(i) != s.charAt(j)) {
j = next[j];
}
if(s.charAt(i) == s.charAt(j)) {
j++;
}
next[i] = j;
}
return next;
}
}
@liuxinglanyue
Copy link
Author

print:

0
0
1
2
3
4
0
1
true

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment