一、题目
二、代码
class Solution
{
public int strStr(String haystack, String needle)
{
int[] next = new int[needle.length()];
getNext(next,needle);
int j = 0;
int length = haystack.length();
for(int i = 0;i<length;i++)
{
while(j>0&&needle.charAt(j)!=haystack.charAt(i)) j = next[j-1];
if(needle.charAt(j) == haystack.charAt(i)) j++;
if(j==needle.length())
{
return i-needle.length()+1;
}
}
return -1;
}
public void getNext(int[] next, String s)
{
int i,j = 0;
next[0] = 0;
int length = next.length;
for(i = 1;i<length ;i++)
{
while(j>0&&s.charAt(j)!=s.charAt(i)) j = next[j-1];
if(s.charAt(j) == s.charAt(i)) j++;
next[i] = j;
}
}
}
三、运行结果