# 【Leetcode】java实现KMP算法

``````	//求NEXT数组
public int[] makeNext(String P)
{
int q,k;
int[] next = new int[P.length()];
next[0] = 0;
for (q = 1,k = 0; q < P.length(); ++q)
{
while(k > 0 && P.charAt(q) != P.charAt(k))
k = next[k-1];
if (P.charAt(q) == P.charAt(k))
k++;
next[q] = k;
}
return next;
}
//返回每次移动的值
public int get_step(String haystack, String needle,int next[],int count)
{
if(haystack.substring(count, needle.length()+count).equals(needle)) return -1;
for(int i = needle.length();i>0;i--)
{
if(haystack.substring(count, i+count).equals(needle.substring(0, i))  )
return needle.substring(0, i).length()-next[i-1];
}
return 1;
}
//主函数，输入两个字符串，返回匹配的第一个下标
public int strStr(String haystack, String needle) {
if(haystack.equals("")&&needle.equals("")) return 0;
if(needle.equals("")) return 0;
if(haystack.length()<needle.length()) return -1;
int count=0,step =0;;
int[] next = makeNext(needle);
while (count<=haystack.length()-needle.length())
{
step  = get_step(haystack, needle, next,count);
if(step!=-1)
count+=step;
else
return count;
}
return -1;
}``````
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。