Leetcode每日一题:28.implement-strstr(实现strStr())_hash

思路:KMP实现虽然效率高,但较为复杂;
这里索性直接hash,注意int溢出,一定要取余

Leetcode每日一题:28.implement-strstr(实现strStr())_ico_02

int strStr(string haystack, string needle)
{
    int len1 = haystack.length();
    int len2 = needle.length();
    if (len2 == 0)
        return 0;
    if (len1 < len2)
        return -1;
    vector<int> res;
    for (int i = 0; i <= len1 - len2; i++)
    {
        long hash = 0;
        int iCopy = i;
        for (int k = 0; k < len2; k++)
        {
            hash = hash * 27 + haystack[iCopy++] - 'a';
            if (hash > INT_MAX)
                hash = hash % INT_MAX;
        }
        res.push_back(hash);
    }
    long hashNeedle = 0;
    for (int k = 0; k < len2; k++)
    {
        hashNeedle = hashNeedle * 27 + needle[k] - 'a';
        if (hashNeedle > INT_MAX)
            hashNeedle = hashNeedle % INT_MAX;
    }
    for (int i = 0; i < res.size(); i++)
    {
        if (res[i] == hashNeedle)
            return i;
    }
    return -1;
}