Created
June 16, 2015 15:46
-
-
Save liuxinglanyue/82c1fdae747a90c79305 to your computer and use it in GitHub Desktop.
KMP算法,查找子串
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
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
print:
0
0
1
2
3
4
0
1
true