# Implement strStr()

Implement strStr().

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

Update (2014-11-02):
The signature of the function had been updated to return the index instead of the pointer. If you still see your function signature returns achar * or String, please click the reload button to reset your code definition.

//事后Time Limit Exceeded，发现我想多了，M*N的时间复杂度也是不行
//只能KMP啦！

if(haystack==""&& needle=="") return 0;//空串考虑
if(haystack=="") return -1;//空串中查找非空串，肯定报错
if(needle=="") return 0;//子串为空

int i=0;
int j=0;

int hlen=haystack.length();
int nlen=needle.length();
if(nlen>hlen) return -1;

int k=i;
while(i!=hlen && j!=nlen)
{
if(haystack[i+j]==needle[j]) ++j;
else{
j=0;
++i;
}
}
if(j==nlen) return i;
else return -1;


void get_next(string needle,vector<int> &next)//next
{
int nlen=needle.size();
int k=-1,j=0;
next.push_back(-1);
while(j!=nlen)
{
if(k==-1 || needle[k]==needle[j])//-1很巧妙
{
j++;
k++;
if(needle[k]!=needle[j])
next.push_back(k);
else next.push_back(next[k]);
}
else
k=next[k];
}

}
int strStr(string haystack, string needle) {

//只能KMP啦！

if(haystack.empty() && needle.empty()) return 0;
if(haystack.empty()) return -1;
if(needle.empty()) return 0;
vector<int> next;
get_next(needle,next);

int hlen=haystack.size(),nlen=needle.size();
if(hlen<nlen) return -1;
int i=0,j=0,index=0;
while(i<hlen && j<nlen)
{
if(haystack[i]==needle[j])//相等
{
++i;
++j;
}

else
{
index=index+j-next[j];
if(next[j]!=-1)  //判断next[j]是否为-1
j=next[j];     //不是-1，那么j回退到next[j]的位置
else              //否则，j回退到0，i右移
{
i++;
j=0;
}
}

}
if(j==nlen) return index;
else return -1;

}

#### LeetCode 28 Implement strStr() (C,C++,Java,Python)

2015-05-12 11:59:17

#### [LeetCode] 028. Implement strStr() (Easy) (C++/Python)

2015-03-06 15:05:22

#### Implement strStr() -- LeetCode

2014-03-02 06:42:01

#### 28. Implement strStr() [easy] (Python)

2016-06-19 01:25:02

#### [LeetCode][Java] Implement strStr()

2015-07-10 20:43:37

#### leetcode | Implement strStr() | 实现字符串查找函数

2015-07-05 15:29:44

#### 28. Implement strStr()-leetcode-java

2016-05-06 18:50:17

#### [28] Implement strStr()

2016-07-28 00:00:14

#### leetcode 28 Implement strStr() C++

2016-06-17 16:52:28

#### [leetcode-28]implement strstr()(C语言)

2015-07-11 21:42:14