28. Implement strStr()

Andreea
1 min readFeb 19, 2022

Implement strStr().

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

Clarification:

What should we return when needle is an empty string? This is a great question to ask during an interview.

For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().

Example 1:

Input: haystack = "hello", needle = "ll"
Output: 2

Example 2:

Input: haystack = "aaaaa", needle = "bba"
Output: -1

Example 3:

Input: haystack = "", needle = ""
Output: 0
class Solution {
public:
int strStr(string haystack, string needle) {

int pos = haystack.find(needle);

if(pos != string::npos)
return pos;

return -1;
}
};

TIPS:

variable “pos” catch the return value(int) of haystack.find(), which returns the position of the first string that match.

Runtime: 4 ms, faster than 75.08% of C++ online submissions for Implement strStr().

Memory Usage: 6.8 MB, less than 31.03% of C++ online submissions for Implement strStr().

--

--