leetcode 28.实现strStr()(kmp,字符串hash)

本文介绍两种高效的字符串匹配算法:一种基于哈希表的O(m+n)复杂度思路,另一种使用字符串哈希的O(max(m,n))方法。重点讲解了如何避免混淆字符'a'和重复字符'aa',以及两种方法的易错点和应用场景。
摘要由CSDN通过智能技术生成

在这里插入图片描述
在这里插入图片描述
思路一:hash(O(m+n)

class Solution {
public:

    int strStr(string haystack, string needle) {
      
        int len1 = haystack.size(), len2 = needle.size();
        //得到next数组
        vector<int> next(len2);
        next[0] = -1;
        int j = -1;
        for (int i = 1; i < len2; ++i) {
            while (j != -1 && needle[i] != needle[j + 1]) {
                j = next[j];
            }
            if (needle[i] == needle[j + 1]) j++;
            next[i] = j;
        }
        //字符串匹配
        j = -1;
        for (int i = 0; i < len1; ++i) {
            while (j != -1 && haystack[i] != needle[j + 1]) {
                j = next[j];
            }
            if (haystack[i] == needle[j + 1]) j++;
            if (j == len2 - 1) return i - len2 + 1;
        }
        return -1;
    }
};

思路二:字符串hash O(max(m, n))

class Solution {
public:
    using ull = unsigned long long;
    int strStr(string haystack, string needle) {
        //字符串hash
        int n = haystack.size(), m = needle.size();
        if (m > n) return -1;
        ull hash2 = 0;
        int base = 131;
        for (int i = 0; i < m; ++i) {
            hash2 = hash2 * base + (needle[i] - 'a' + 1);
        }
        vector<ull> hash1(n + 1), pow(n + 1);
        pow[0] = 1;
        for (int i = 0; i < n; ++i) {
            hash1[i + 1] = hash1[i] * base + (haystack[i] - 'a' + 1);
            pow[i + 1] = pow[i] * base;
        }
        auto get = [&](int l, int r) {
            return hash1[r] - (hash1[l - 1] * pow[r-l+1]);
        };
        for (int i = 0; i <= n - m; ++i) {
            if (get(i + 1, i + m) == hash2) return i;
        }
        return -1;
    }
};

易错点:
1:防止aa 跟 a 区分不开,因此’a’应该映射到1,因此needle[i] - 'a’要 + 1

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值