题目描述
Java解决方法
KMP算法原理比较难懂,但是还是得会写相对应的程序:
class Solution {
public int strStr(String haystack, String needle) {
//使用的是KMP算法
int hlen = haystack.length();
int nlen = needle.length();
if(nlen == 0)
{
return 0;
}
int[] nextval = new int[nlen];
int i = 0;
int j = 0;
GetNextval(needle,nextval);
while (i < hlen && j < nlen)
{
if (j == -1 || haystack.charAt(i) == needle.charAt(j))
{
i++;
j++;
}
else
{
j=nextval[j];
}
}
if(j >= nlen)
{
return (i-nlen);
}
else
{
return (-1);
}
}
private void GetNextval(String needle,int nextval[])
{
int j = 0;
int k = -1;
nextval[0] = -1;
while (j < needle.length())
{
if (k == -1 || needle.charAt(j) == needle.charAt(k))
{
j++;
k++;
if(j >needle.length() - 1)
{
break;
}
if (needle.charAt(j) != needle.charAt(k))
{
nextval[j] = k;
}
else
{
nextval[j] = nextval[k];
}
}
else
{
k = nextval[k];
}
}
}
}
运行结果: