public void getNext (char mainChr[], int next[]) {
//构造next数组,参数mainChr[]是主元字符串
next[0] = -1;
int behind = 0, front = -1;
//front指向前缀,back指向后缀
while (behind < mainChr.length) {
if (front == -1 || mainChr[behind] == mainChr[front]) {
behind++;
front++;
next[behind] = front;
} else {
//mainChr[behind] != mainChr[front],
//找到之前已经计算过的next[front]继续计算当前字符串的最大前后缀的交集数
front = next[front];
}
}
}
//若存在该子字串,返回该子字符串起始下标,否,返回-1
public int KMP (char[] mainChr, char[] tarChr) {
//参数mainChr是主元字符串,参数tarChr是子字符串。
int mP = 0;
int tP = 0;
while (mP < mainChr.length && tP < tarChr.length) {
if (tP == -1 || mainChr[mP] == tarChr[tP]) {
mP++;
tP++;
} else {
tP = next[tP];
}
}
if (tP == tarChr.length)
return mP-tP;
else
return -1;
}