28. 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: 2

Example 2:

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

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().

Solutions:

class Solution {
public:
    int strStr(string haystack, string needle) {
        if (haystack.length() < needle.length())    return -1;
        if (needle.length() == 0)   return 0;

        const unsigned int MOD = 10000; 
        const unsigned int MUL = 10;

        unsigned int needleHash = 0;
        for (auto c : needle) {
            needleHash = (needleHash * MUL + c - 'a' + 1) % MOD;
        }

        unsigned int haystackHash = 0;
        for (int i = 0; i < needle.length(); ++i) {
            haystackHash = (haystackHash * MUL + haystack[i] - 'a' + 1) % MOD;
        }

        unsigned int highHash = 1;
        for (int i = 0; i < needle.length() - 1; ++i) { // be careful! what if needle size is 0;
            highHash = (highHash * MUL) % MOD;
        }

        for (int i = 0; i < haystack.length() - needle.length() + 1; ++i) {
            if (needleHash == haystackHash && isEqual(haystack, i, needle)) return i;
            if (i == haystack.length() - needle.length()) return -1;
            haystackHash = ((haystackHash + MOD - highHash * (haystack[i] - 'a' + 1) % MOD ) % MOD * MUL + haystack[i+needle.length()] - 'a' + 1) % MOD; // WARNING: don't overflow
        }

        return -1;

    }

    bool isEqual(const string& haystack, int start, const string& needle) {
        for (int i = 0; i < 0 + needle.length(); ++i) {
            if (haystack[i + start] != needle[i])   return false;
        }

        return true;
    }
};

results matching ""

    No results matching ""