本来是一个很简单的问题,大神用五行代码搞定,我却要用四十行代码,不过正好实现下KMP算法,也是一种学习。
题目如下:
其实就是一个字符串匹配的问题,匹配到哪,就输出哪里的下标,否则就输出-1.看到这个题目的时候我一下子就想到了KMP算法,本来以为是省时省力的,没想到运算起来还是蛮慢的。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;
}