JAVA实现KMP模式匹配算法
public int strStr(String haystack, String needle) {
int i=0,j=0;
int[] next=getNext(needle);
while (i< haystack.length() && j<needle.length()){
if (j==-1 || haystack.charAt(i)==needle.charAt(j)){
i++;
j++;
}else {
j=next[j];
}
}
if (j==needle.length())
return i-j;
else
return -1;
}
//求next[]数组,next[0]=-1 当遇到冲突时直接查next数组并且返回到相应位置
private static int[] getNext(String sub){
int[] next=new int[sub.length()+1];
int i=0;
int j=-1;
next[0]=-1;
while (i<sub.length()){
if (j==-1 || sub.charAt(i) == sub.charAt(j)){
next[++i]=++j;
}else {
j=next[j];
}
}
return next;
}
今日推歌
----《大眠》
都快忘了怎样恋一个爱
我被虚度了的青春
也许还能活过来
说心疼我的更应该明白
我当然会沉醉个痛快