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;
    }
};

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章