[LeetCode] Implement strStr()

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

使用KMP算法来overwrite strStr()

class Solution {
public:
    int strStr(string haystack, string needle) {
        if(needle.empty()) return 0;
        if(haystack.empty()) return -1;
        return kmp(haystack, needle);
    }
    
    int kmp(string haystack, string needle)
    {
        vector<int> next = getNext(needle); 
        int sLen = haystack.size(), tLen = needle.size();
        int i = 0, j = 0, res = -1;
        while (i < sLen)
        {
            if (j == -1 || haystack[i] == needle[j])
            {
                ++i;
                ++j;
            }
            else
            {
                j = next[j];
            }
            if (j == tLen)
            {
                res = i - tLen;
                break;
            }
        }
        return res;
    }
    
    vector<int> getNext(string needle)
    {
        vector<int> next(needle.size(), -1);
        int tLen = needle.size();
        int i = 0, j = -1;
        while (i < tLen - 1)
        {
            if (j == -1 || needle[i] == needle[j])
            {
                ++i;
                ++j;
                next[i] = j;
            }
            else
            {
                j = next[j];
            }
        }
        return next;
    }
};
// 7 ms
原文地址:https://www.cnblogs.com/immjc/p/8543882.html