KMP& sunday

这篇博客探讨了三种不同的C++字符串模式匹配算法:Sunday算法、KMP算法和使用标准库函数的实现。文中详细展示了每种算法的代码实现,并比较了它们在查找子字符串时的效率和适用场景。通过对字符串处理技术的深入理解,开发者可以更好地选择适合项目需求的算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

模式匹配算法c++实现

class Solution {//sunday
public:
    int strStr(string haystack, string needle) {
        int n = haystack.size(), m = needle.size();

        unordered_map<char,int> shift;
        for(int i = 0; i < m; ++i){
            shift[needle[i]] = m - i;//计算在每个字符需要移位的多少
        }
        
        int idx = 0,i = 0;
        while(idx < n){
            for(i = 0; i < m; ++i){
                if(haystack[idx+i] != needle[i]){
                    break;
                }
            }

            if(i == m) return idx;//匹配成功
            if(idx+m>n) return -1;//防止越界
            if(shift[haystack[idx+m]]){//后一个在之前的范围内则可以移动部分区域
                idx += shift[haystack[idx+m]];
            }else{//后一个不在范围内 直接放弃这块区域
                idx += m+1;
            }
        }
        return -1;
    }
};
class Solution {//kmp
public:
    int strStr(string haystack, string needle) {
        int n = haystack.size(), m = needle.size();
        if (m == 0) {
            return 0;
        }
        vector<int> pi(m);
        for (int i = 1, j = 0; i < m; i++) {
            while (j > 0 && needle[i] != needle[j]) {
                j = pi[j - 1];
            }
            if (needle[i] == needle[j]) {
                j++;
            }
            pi[i] = j;
        }
        for (int i = 0, j = 0; i < n; i++) {
            while (j > 0 && haystack[i] != needle[j]) {
                j = pi[j - 1];
            }
            if (haystack[i] == needle[j]) {
                j++;
            }
            if (j == m) {
                return i - m + 1;
            }
        }
        return -1;
    }
};
class Solution {//kmp
public:
void nextT(string &t, vector<int> &next,int n)
{
    int j = 0, k = -1;
    next[0] = -1;
    while(j < n-1) {
        if(k == -1 || t[j] == t[k]) {
            next[++j] = ++k;
        } else {
            k = next[k];
        }
    }
}
int KMP(string &s, string &t)
{
    int m = s.size();
    int n = t.size();
    int i = 0, j = 0;
    vector<int> next(n);
    nextT(t,next,n);

    while(i < m && j < n) {
        if(j == -1 || s[i] == t[j]) {
            ++i;
            ++j;
        } else {
            j = next[j];
        }
    }
    if(j == n)
        return i - j;
    return -1;
}

int strStr(string haystack, string needle)
{
    return KMP(haystack,needle);
}
};
class Solution {
public://库函数
int strStr(string haystack, string needle)
{
    return haystack.find(needle);
}
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值