The Description of the problem
Given two strings needle
and haystack
, return the index of the first occurrence of needle
in haystack
, or -1 if needle
is not part of haystack
.
Example 1:
Input: haystack
= “sadbutsad”, needle
= “sad”
Output: 0
Explanation: “sad” occurs at index 0 and 6. The first occurrence is at index 0, so we return 0.
Example 2:
Input: haystack
= “leetcode”, needle
= “leeto”
Output: -1
Explanation: “leeto” did not occur in “leetcode”, so we return -1.
The codes in Python
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if len(needle) == 0:
return 0
# get next array
next = [0]
pos = 0
for i in range(1, len(needle)):
while pos != 0 and needle[pos] != needle[i]:
pos = next[pos - 1]
if needle[pos] == needle[i]:
pos += 1
next.append(pos)
# find the index of the first occurrence of needle in haystack
j = 0
for i in range(len(haystack)):
while j >= 1 and haystack[i] != needle[j]:
j = next[j - 1]
if haystack[i[ == needle[j]:
j += 1
if j == len(needle):
return i - j + 1
return -1
The codes in C++
The codes with a bug (Can you find it and fix it)
class Solution {
public:
int strStr(string haystack, string needle) {
if (needle.size() == 0) {
return 0;
}
// get the next array
vector<int> next = {0};
int pos = 0;
for (int i = 1; i < needle.size(); i++) {
while (pos > 0 && needle[pos] != needle[i]) {
pos = needle[pos - 1];
}
if (needle[pos] == needle[i]) {
pos++;
}
next.push_back(pos);
}
// find the index of the first occurrence of needle in haystack
int j = 0;
for (int i = 0; i < haystack.size(); i++) {
while (j > 0 && haystack[i] != needle[j]) {
j = next[j - 1];
}
if (haystack[i] == needle[j]) {
j++;
}
if (j == needle.size()) {
return i - needle.size() + 1;
}
}
return -1;
}
};
The C++ codes with bug free
class Solution {
public:
int strStr(string haystack, string needle) {
if (needle.size() == 0) {
return 0;
}
// get the next array
vector<int> next = {0};
int pos = 0;
for (int i = 1; i < needle.size(); i++) {
while (pos > 0 && needle[pos] != needle[i]) {
pos = next[pos - 1];
}
if (needle[pos] == needle[i]) {
pos++;
}
next.push_back(pos);
}
// find the index of the first occurrence of needle in haystack
int j = 0;
for (int i = 0; i < haystack.size(); i++) {
while (j > 0 && haystack[i] != needle[j]) {
j = next[j - 1];
}
if (haystack[i] == needle[j]) {
j++;
}
if (j == needle.size()) {
return i - needle.size() + 1;
}
}
return -1;
}
};