# 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 a char * or String, please click the reload button to reset your code definition.

Solution:

class Solution {
public:
void getNext(string needle, vector<int> &next)
{
int i = 0, j = -1;
next[i] = j;
while(i < needle.length())
{
while(j != -1 && needle[i] != needle[j]) j = next[j];
next[++i] = ++j;
}
}

int strStr(string haystack, string needle) {
vector<int> next(needle.length()+1);
getNext(needle, next);
int i = 0, j = 0;
int hlen = haystack.length();
int nlen = needle.length();
while(i < hlen && j < nlen)
{
if(j == -1 || haystack[i] == needle[j])
{
++i;
++j;
}
else
{
j = next[j];
}
}
if(j == nlen) return i - j;
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