leetcode28 實現 strStr()--KMP算法應用(hard)

題目

實現 strStr() 函數。

給定一個 haystack 字符串和一個 needle 字符串,在 haystack 字符串中找出 needle 字符串出現的第一個位置 (從0開始)。如果不存在,則返回  -1。

示例 1:

輸入: haystack = "hello", needle = "ll"
輸出: 2
示例 2:

輸入: haystack = "aaaaa", needle = "bba"
輸出: -1
說明:

當 needle 是空字符串時,我們應當返回什麼值呢?這是一個在面試中很好的問題。

對於本題而言,當 needle 是空字符串時我們應當返回 0 。這與C語言的 strstr() 以及 Java的 indexOf() 定義相符。

 

KMP實現

這篇博客 和 這篇

next數組的實現:

求X位置的最大前綴匹配,連續不匹配的情況:

求x位置的最大前綴匹配,往前能找到的情況

class Solution {
public:
    vector<int> getNext(string s){
        int n = s.size(),cnt = 0;
        vector<int> next(n,0);
        next[0] = -1;

        // 注意這裏不自動+1
        for(int i = 2;i < n;){
            // 相同時
            if(s[cnt] == s[i-1]) next[i++] = ++cnt;
            else{
                // 不同時,往前找cnt位置的最大匹配
                if(cnt > 0) cnt = next[cnt];
                else next[i++] = 0;
            }
        }
        return next;
    }

    // kmp實現
    int strStr(string haystack, string needle) {
        if(needle.empty()) return 0;
        vector<int> next = getNext(needle);
        int i = 0,j = 0;
        while(i < needle.size() && j < haystack.size()){
            if(haystack[j] == needle[i]){
                i++;j++;
            }else{
                if(next[i] == -1) j++;
                else i = next[i];
            }
        }
        if(i == needle.size()){
            return j-i;
        }
        return -1;
    }
};

 

 

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