//參考http://www.cnblogs.com/linbingdong/p/6479537.html
//http://blog.csdn.net/henuyx/article/details/44653799
//http://www.cnblogs.com/tangzhengyue/p/4315393.html
package string;
public class KMPSearch {
public static void main(String[] args) {
// TODO Auto-generated method stub
String txt = "yuchengxin is good man";
String pat = "good";
int[] next = new int[pat.length()];
getNext(pat, next);
System.out.println(Search(txt, pat, next));
}
//next數(shù)組為pat跳轉(zhuǎn)記錄狀態(tài)的數(shù)組秽澳,此處是關(guān)鍵岂嗓,注意理解
public static int[] getNext(String pat, int[] next) {
int N = pat.length();
next[0] = -1;//初始條件next[0]=-1,next[1]=0
int k = -1;
int j = 0;
while (j < N - 1) {
if (k == -1 || pat.charAt(j) == pat.charAt(k)) {
next[++j] = ++k; //若相等,則j的下一個跳到k的下一個處
if (pat.charAt(j) == pat.charAt(k)) {
next[j] = next[k];//若繼續(xù)相等御铃,則再往前跳
}
} else {
k = next[k];//不相等則移回到k處
}
}
return next;
}
public static int Search(String txt, String pat, int[] next) {
int M = txt.length();
int N = pat.length();
int i = 0, j = 0;
while (i < M && j < N) {
if (j == -1 || txt.charAt(i) == pat.charAt(j)) {
j++;
i++;
} else {
j = next[j];
}
}
if (j == N)
return i - j;
else
return -1;
}
}
//參考算法第四版代碼
package string;
public class BoyerMooreSearch {
//注意此處right[]的構(gòu)造
public static void getRight(String pat, int[] right) {
for (int i = 0; i < 256; i++) {
right[i] = -1;
}
for (int j = 0; j < pat.length(); j++) {
right[pat.charAt(j)] = j;
}
}
public static int Search(String txt, String pat, int[] right) {
int M = txt.length();
int N = pat.length();
int skip;
for (int i = 0; i < M - N; i += skip) {
skip = 0;
for (int j = N - 1; j >= 0; j--) {
if (pat.charAt(j) != txt.charAt(i + j)) {
skip = j - right[txt.charAt(i + j)];
if (skip < 1)
skip = 1;
break;
}
}
if (skip == 0)
return i;
}
return -1;
}
public static void main(String[] args) {
String txt = "THIS IS A BIG TIGER";
String pat = "IG";
int[] right = new int[256];
getRight(pat, right);
System.out.println(Search(txt, pat, right));
}
}