leetcode 第 28 题:实现 strStr()(C++)

28. 实现 strStr() - 力扣(LeetCode)
在这里插入图片描述

简单题

暴力匹配

class Solution {
public:
    int strStr(string haystack, string needle) {
        if(needle.empty())  return 0;
        if(needle.size() > haystack.size()) return -1;
        int i = 0, n = haystack.size(), m = needle.size();
        while(i < n-m+1){
            if(haystack[i] != needle[0] || haystack[i+m-1] != needle[m-1]){//先判断首尾是否相同
                ++i;
                continue;
            }
            else if(haystack.substr(i, m) == needle)    return i;
            else ++i;
        }
        return -1;
    }
};

其实这个方法虽然是暴力法,但是只要首先考虑首尾,最后效率会很快(比下面的都要快)。

KMP

关于kmp算法,可以看这儿:
数据结构与算法之美:34 | 字符串匹配基础(下):如何借助BM算法轻松理解KMP算法?_qq_32523711的博客-CSDN博客

class Solution {
public:
    void getNexts(vector<int> &next, string &s, int m){
        int k = -1; //最长匹配前缀字串末尾字符下标(-1代表不存在)
        for(int i = 1; i < m; ++i){
            while(k != -1 && s[k+1] != s[i])
                k = next[k];
            if(s[k+1] == s[i])  ++k;
            next[i] = k;
        }
    }
    int strStr(string haystack, string needle) {
        if(needle.empty())  return 0;
        vector<int> next(needle.size(), -1);
        getNexts(next, needle, needle.size());
        int j = 0;//在needle上遍历
        for(int i = 0; i < haystack.size(); ++i){//在haystack上遍历
            while(j > 0 && haystack[i] != needle[j]){// i 为坏字符
                j = next[j-1]+1;//更新 j 的位置,继续从位置 i 开始匹配
            }
            if(haystack[i] == needle[j])    ++j;
            if(j == needle.size())  return i-needle.size()+1;
        }
        return -1;
    }
};

RK算法

介绍可以看:
数据结构与算法之美:32 | 字符串匹配基础(上):如何借助哈希算法实现高效字符串匹配?_qq_32523711的博客-CSDN博客

简单的哈希函数加上二次验证:

class Solution {
public:
    int strStr(string haystack, string needle) {
        int m = haystack.size(), n = needle.size();
        if(n == 0)  return 0;
        int hash_h = 0, hash_n = 0;
        for(int i = 0; i < n; ++i){
            hash_h += pow(haystack[i] - 'a', 2);
            hash_n += pow(needle[i] - 'a', 2);
        }
        if(hash_h == hash_n && haystack.substr(0, n) == needle)    return 0;//最开始就刚好匹配
        for(int i = 1; i < m-n+1; ++i){//在haystack上遍历
            hash_h = hash_h-pow(haystack[i-1]-'a',2) + pow(haystack[i+n-1]-'a', 2);
            if(hash_h == hash_n)
                if(haystack.substr(i, n) == needle) return i; //二次验证
        }
        return -1;
    }
};
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值