28. Implement strStr()
https://leetcode.com/problems/implement-strstr/
Problem
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1Clarification:
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().
Constraints:
haystackandneedleconsist only of lowercase English characters.
Solution
class Solution {
public:
int strStr(string &haystack, string &needle) {
if (needle.empty()) return 0;
const int max_index = static_cast<int>(haystack.size()) - static_cast<int>(needle.size());
for (int i = 0; i < max_index + 1; ++i) {
for (int j = 0; j < needle.size(); ++j) {
if (haystack[i + j] != needle[j]) break;
if (j == needle.size() - 1) return i;
}
}
return -1;
}
};#string
#important
#kmp
Last updated
Was this helpful?