c++ 字符串匹配算法sunday算法

本文介绍了一种名为Sunday的C++字符串匹配算法,它比KMP算法实现更简单。Sunday算法通过构造一个mp数组,实现了快速字符查找和字符串定位。实例演示了如何使用Sunday类进行字符串搜索操作。
摘要由CSDN通过智能技术生成

sunday 算法是一种很高效的字符串匹配算法, 其实现也较kmp算法简单很多

class Sunday {
public:
    const string& needle;
    int mp[300];

    Sunday(const string& needle) : needle(needle) {
        fill(mp, mp + 300, -1);
        for (int i = 0; i < needle.size(); i++) {
            mp[needle[i]] = i;
        }
    }
    int advance(char c) {
        int n = mp[c];
        return (int)needle.size() - n;
    }

    void advance(int& i, int &j, char c) {
        i += advance(c);
        j = 0;
    }

    int strstr(const string& target) {
        int i = 0, j = 0;
        while (i + needle.size() < target.size() + 1) {
            if (needle[j] == target[i + j]) {
                if (++j == needle.size()) {
                    return i;
                }
            } else {
                advance(i, j, target[i + needle.size()]);
            }
        }
        return -1;
    }
};

class Solution {
public:
    int strStr(string haystack, string needle) {
        Sunday sun(needle);
        return sun.strstr(haystack);
    }
};

c++ 字符串匹配算法sunday算法
c++ 字符串匹配算法sunday算法
c++ 字符串匹配算法sunday算法
c++ 字符串匹配算法sunday算法
c++ 字符串匹配算法sunday算法
c++ 字符串匹配算法sunday算法
c++ 字符串匹配算法sunday算法
c++ 字符串匹配算法sunday算法
c++ 字符串匹配算法sunday算法
c++ 字符串匹配算法sunday算法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值