# Implement strStr

输入: haystack = "hello", needle = "ll"


public int strStr_2(String haystack, String needle) {
if(haystack.length() < needle.length())
return -1;
if(needle.length() == 0)
return 0;
int h = haystack.length(),n = needle.length();
for(int i = 0; i <= h-n; i++){//不需要遍历完,因为到后面长度就不符合了
int j = 0;
for(j = 0; j < n; j++){
if(haystack.charAt(i+j) != needle.charAt(j))
break;
}
System.out.println(j);
if(j == n)
return i;

}
return -1;

}

public int strStr_3(String haystack, String needle) {
if(haystack.length() < needle.length())
return -1;
if(needle.length() == 0)
return 0;
int h = haystack.length(),n = needle.length();
for(int i = 0; i <= h-n; i++){
if(haystack.substring(i, i+n).equals(needle)){
return i;
}
}
return -1;

}

private void GetNext(String needle,int next[])
{
int pLen = needle.length();
next[0] = -1;
int k = -1;
int j = 0;
while (j < pLen - 1)
{
//p[k]表示前缀，p[j]表示后缀
if (k == -1 || needle.charAt(j) == needle.charAt(k))
{
++k;
++j;
next[j] = k;
}
else
{
k = next[k];
}
}
}
public int KmpSearch(String haystack, String needle)  //kmp
{
if(haystack.length() < needle.length())
return -1;
if(needle.length() == 0)
return 0;
int i = 0;
int j = 0;
int[] next = new int[needle.length()];
GetNext(needle, next);
int sLen = haystack.length();
int pLen = needle.length();
while (i < sLen && j < pLen)
{
//①如果j = -1，或者当前字符匹配成功（即S[i] == P[j]），都令i++，j++
if (j == -1 || haystack.charAt(i) == needle.charAt(j))
{
i++;
j++;
}
else
{
//②如果j != -1，且当前字符匹配失败（即S[i] != P[j]），则令 i 不变，j = next[j]
//next[j]即为j所对应的next值
j = next[j];
}
}
if (j == pLen)
return i - j;
else
return -1;
}

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120