KMP算法记录

关于算法介绍,可以参考july的文章https://www.cnblogs.com/v-July-v/archive/2011/06/15/2084260.html

这里主要做一个记录,为了今后翻阅方便

题目:https://leetcode.com/problems/implement-strstr/description/

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

代码:

class Solution {
public:
    
    void getNext(string needle, int next[])
    {
        int len = needle.length();
        next[0] = -1;
        int k = -1;
        int j = 0;
        while(j < len -1)
        {
            // p[k] 表示前缀,p[j] 表示后缀
            if(k == -1 || needle[j] == needle[k])
            {
                ++j;
                ++k;
                next[j] = k;
            }
            else
                k = next[k];
        }
    }
    
    int strStr(string haystack, string needle) {
        int hLen = haystack.length();
        int nLen = needle.length();
        int i = 0, j = 0;
        int *next = new int[100005];
        getNext(needle,next);
        while(i < hLen && j < nLen)
        {
            if(j ==-1 || haystack[i] == needle[j])
            {
                i++;
                j++;
            }
            else
                j = next[j];
        }
        if(j == nLen)
            return i - j;
        else return -1;
    }
};

点赞