# 28. Implement strStr()（String字符串匹配）

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Subscribe to see which companies asked this question

public class Solution {
public int[] next;
public int strStr(String haystack, String needle) {
if(needle.isEmpty())return 0;
if(haystack.isEmpty())return -1;
next = new int[needle.length()+1];
getNext(needle);
int j=0,i=0;
while(i<haystack.length())
{
while(j>=0 && haystack.charAt(i)!=needle.charAt(j))j=next[j+1]-1;
j++;
i++;
if(j==needle.length())return i-j;
}
return -1;
}

public void getNext(String str)
{
//next从1开始
int i=1,f=0;
while(i<str.length())
{
//找到满足pattern[k] = pattern[j]的最大k值。
while(f>0 && str.charAt(i-1)!=str.charAt(f-1))
{
f=next[f];
}
i++;
f++;
if(str.charAt(i-1)==str.charAt(f-1))
{
next[i]=next[f];
}
else
{
next[i]=f;
}
}
}
}

public class Solution {
public int strStr(String haystack, String needle) {
if(needle.isEmpty())return 0;
if(haystack.isEmpty())return -1;
int[] dic = new int[26];
for(int i=0;i<26;i++)
{
dic[i]=needle.length()+1;
}
for(int i=0;i<needle.length();i++)
{
//设置每个字符离needle尾字符的长度加一
dic[needle.charAt(i)-'a']=needle.length()-i;
}
//目标字符串与模式串对其位置
int pos=0;
int i,j;
while(pos<haystack.length()-needle.length()+1)
{
i=pos;
for(j=0;j<needle.length();++j,++i)
{
if(haystack.charAt(i)!=needle.charAt(j))
{
//查找目标串中，与模式串对齐最后一个字符的后面那个字符ch，
//并查找模式串中等于ch的字符，使之与目标串的ch对齐
if(pos+needle.length()<haystack.length()-needle.length()+1)
pos+=dic[haystack.charAt(pos+needle.length())-'a'];
else pos++;
break;
}
}
if(j==needle.length())return pos;
}

return -1;
}
}

http://blog.163.com/yangfan876@126/blog/static/80612456201342205056344/

• 本文已收录于以下专栏：

举报原因： 您举报文章：28. Implement strStr()（String字符串匹配） 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)