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.
class Solution:def strStr(self, haystack: str, needle: str) -> int:if len(needle) == 0:return 0# get next arraynext = [0]pos = 0for i in range(1, len(needle)):while pos != 0 and needle[pos] != needle[i]:pos = next[pos - 1]if needle[pos] == needle[i]:pos += 1next.append(pos)# find the index of the first occurrence of needle in haystackj = 0for i in range(len(haystack)):while j >= 1 and haystack[i] != needle[j]:j = next[j - 1]if haystack[i[ == needle[j]:j += 1if j == len(needle):return i - j + 1return -1
class Solution {
public:int strStr(string haystack, string needle) {if (needle.size() == 0) {return 0;}// get the next arrayvector 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 haystackint 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;}
};
class Solution {
public:int strStr(string haystack, string needle) {if (needle.size() == 0) {return 0;}// get the next arrayvector 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 haystackint 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;}
};