复杂算法介绍[2]-KMP算法代码实现
直接上代码:
public class Kmp {
/**
* 算是比较难的算法之1,看了很多遍,经常忘记
*
* 1、给定一个字符串,求某个位置字符之前字符串最长前缀和后缀匹配长度
* abcabck
*
* 在k位置,就是从长度是1开始遍历
* l = 1,前缀是a,后缀是c
* l = 2,前缀是ab,后缀是bc
* l = 3,前缀是abc,后缀是abc 相等
* l = 4,前缀是abca,后缀cabc
* l = 5,前缀是abcab,后缀bcabc
* l 不能等于字符串长度
* 多以k位置最长前缀和后缀长度是3
*
* 假设有个字符串s=abcabcfabc和该字符串在k位置匹配不上
* s:abcabc f abc
* |
* m:abcabc k
*
* 那么下一次当然可以从主串 1位置开始重新匹配,但是真的需要吗?
*
* 具体的证明请看文档Kmp算法【有点复杂】
*
*
*/
public static int[] getNext1(String str){
char[] chars = str.toCharArray();
if(chars.length<0){
return null;
}
int[] res = new int[chars.length];
res[0]=-1;
if(chars.length==1){
return res;
}
res[1]=0;
if(chars.length==2){
return res;
}
int j =0;
for(int i =2;i<chars.length;i++){
while(j>=0){
if(chars[j]==chars[i-1]){
break;
}else{
j = res[j];
}
}
if(j<0){
res[i]=0;
j=0;
}else{
res[i]=++j;
}
}
return res;
}
public static int[] getNext2(String str){
char[] chars = str.toCharArray();
if(chars.length<0){
return null;
}
int[] res = new int[chars.length];
res[0]=-1;
if(chars.length==1){
return res;
}
res[1]=1;
if(chars.length==2){
return res;
}
int j =0;
for(int i =2;i<chars.length;i++) {
while (j >= 0) {
if (chars[j] == chars[i - 1]) {
break;
} else {
j = res[j];
}
}
if (chars[i] == chars[j + 1]) {
res[i] = res[j + 1];
++j;
} else {
if (j < 0) {
res[i] = 0;
j = 0;
} else {
res[i] = ++j;
}
}
}
return res;
}
public static int match1(String s,String m){
if(s.length()<m.length()||s.length()<=0||m.length()<=0){
return -1;
}
int[] next1 = getNext2(m);
int j = 0;
int res = -1;
char[] sBytes = s.toCharArray();
char[] mBytes = m.toCharArray();
for (int i = 0; i < sBytes.length;) {
if(sBytes[i] == mBytes[j]){
i++;
j++;
}else{
j = next1[j];
if(j==-1){
j=0;
}
}
if(j==mBytes.length){
res = i-j;
break;
}
}
return res;
}
public static void main(String[] args) {
String str="ababc";
String pattern = "abc";
// String str2="aaaaad";
int[] next1 = getNext1(pattern);
System.out.println(Arrays.toString(next1));
System.out.println(match1(str,pattern));
}
}