一、题目
![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/7e85f37a38a34872be32298e896247e0.png)
二、代码
class Solution
{
public int strStr(String haystack, String needle)
{
int i,j ;
int length_needle = needle.length();
int[] next = new int[length_needle];
next[0] = 0;
int index = 0;
for(i=1;i<length_needle;i++)
{
while(index>0&&needle.charAt(i)!= needle.charAt(index))
{
index = next[index-1];
}
if(needle.charAt(i) == needle.charAt(index)) index++;
next[i] = index;
System.out.println(" i "+i+" "+next[i]);
}
int length_haystack = haystack.length();
index = 0;
for(i=0;i<length_haystack;i++)
{
while(index>0&&haystack.charAt(i)!=needle.charAt(index))
{
index = next[index-1];
}
System.out.println(" i "+i);
System.out.println(" index " +index);
System.out.println(" ");
if(haystack.charAt(i)==needle.charAt(index)) index++;
if(index == length_needle) return i-length_needle+1;
}
return -1;
}
}
三、运行结果
![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/8b4737275d8544a680767e98d52185d9.png)