子串判定算法(KMP&字符串哈希)

題目描述

給定字符串haystackneedle,判定needle是否是haystack的子串。以下給出的兩種算法複雜度均爲O(m)
傳送門:Leetcode 28

KMP算法

首先計算needlenext數組,隨後執行KMP算法。

class Solution
{
public:
    int strStr(string haystack, string needle)
    {
        if (needle.empty())
            return 0;

        int m = haystack.size();
        int n = needle.size();

        // 'next' array of needle
        vector<int> next(n);
        next[0] = -1;

        int j = -1;
        for (int i = 1; i < n; ++i)
        {
            while (j != -1 && needle[i] != needle[j + 1])
                j = next[j];
            if (needle[i] == needle[j + 1])
                ++j;
            next[i] = j;
        }

        // kmp algorithm
        j = -1;
        for (int i = 0; i < m; ++i)
        {
            while (j != -1 && haystack[i] != needle[j + 1])
                j = next[j];
            if (haystack[i] == needle[j + 1])
                ++j;

            if (j == n - 1)
                return i - n + 1;
        }

        return -1;
    }
};

字符串哈希算法

哈希值 = 26進制字符串

class Solution
{
public:
    int strStr(string haystack, string needle)
    {
        const long long mod = 10e9 + 7;
        int m = haystack.length();
        int n = needle.length();

        if (m < n) return -1;

        long long h_hash = 0;
        long long n_hash = 0;

        long long pow = 1;              // 計算26^n
        
        // 計算原始窗口的哈希值
        for (int i = 0; i < n; ++i)
        {
            pow = (pow * 26) % mod;
            h_hash = (h_hash * 26 + haystack[i] - 'a') % mod;
            n_hash = (n_hash * 26 + needle[i] - 'a') % mod;
        }

        if(h_hash == n_hash) return 0;

        // 移動窗口,動態計算哈希值
        for (int l = 0, r = n; r < m; ++l, ++r)
        {
            h_hash = (h_hash * 26 - pow * (haystack[l] - 'a') + haystack[r] - 'a') % mod;
            if(h_hash == n_hash) return l + 1;
        }

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