28. Implement strStr()

1. Description

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

2. Example

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

3. Constraints

  • 0 <= haystack.length, needle.length <= 5 * $10^4$
  • haystack and needle consist of only lower-case English characters.

4. Solutions

My Accepted Solution

m = haystack.size(), n = needle.size()
Time complexity: O(mn)
Space complexity: O(1)

class Solution {
public:
    int strStr(const string &haystack, const string &needle) {
        for (int i = 0; i + needle.size() <= haystack.size(); ++i) {
            if (haystack.substr(i, needle.size()) == needle) {
                return i;
            }
        }

        return -1;
    }
};

KMP

// TODO
comments powered by Disqus