【C++】从字符串中匹配字符串,leetcode28

本文介绍了四种字符串匹配算法:strstr、memmem、SUNDAY搜索算法(基于移动窗口)和KMP算法(通过next数组减枝)。着重讲解了每种算法的工作原理和应用场景。

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

字符串匹配子字符串可以使用以下四种算法:memmem、strstr、sundaysearch函数、KMP算法

不止这四种了,以下面一点点更新数量为准,hh

1、strstr

首先,我使用最多是strstr函数,若可以匹配到子字符串则返回子字符串的首字母的指针,若不能匹配到则返回NULL;

#include <iostream>
#include <cstring>

using namespace std;

int main(){
        string a = "abcdefg";
        string b = "bcd";
        const char * pos = strstr(a.c_str(), b.c_str());
        if (pos) {
            cout << "找到子串,位置在:" << pos-a.c_str() << endl;
        } else {
            cout << "未找到子串" << endl;
        }
        return 0;
}

结果返回:

此代码中的pos后续不能更改;若想更改,不妨加上 const_cast。

2、memmem

memmem与strstr函数类似

#include <iostream>
#include <cstring>

using namespace std;
int main(){
    string a = "abcdefg";
    string b = "bcd";
    const void* a_ptr = reinterpret_cast<const void*>(a.c_str());
    const void* b_ptr = reinterpret_cast<const void*>(b.c_str());
    auto pos = reinterpret_cast<const char*>(memmem(a_ptr, a.size(), b_ptr, b.size()));
    if (pos) {
        cout << "找到子串,位置在:" << pos - a.c_str() << endl;
    } else {
        cout << "未找到子串" << endl;
    }
    return 0;
}

结果返回

一般情况下 memmem比strstr更快一些。

3、sundaysearch

"SUNDAY 搜索算法"是一种用于字符串匹配的算法。它是根据字符串匹配中常见的"移动窗口"的思想,在搜索过程中尽可能减少比较次数,提高匹配效率。

"SUNDAY 搜索算法"的基本思想如下:

匹配过程:从待搜索的字符串的开头开始,逐个字符与模式串进行匹配。如果当前字符与模式串中对应位置的字符相等,则比较下一个字符;如果不相等,则判断主字符串的下一字节是否在子字符串中出现过:

1、若未出现过,则从主字符串的下一字符开始匹配子字符串;

2、若出现过则,则将子字符串中相同的字符与主字符串相对齐(若子字符串中有相同的字符,则选择最右的字符)。

因此需要一个跳跃表格,记录字符最右出现的位置。

#include <iostream>
#include <string>
#include <vector>
#include <bits/stdc++.h>
using namespace std;

vector<int> sunday(const string & mainstr, const string &substr) {
        vector<int> result;
        int n = mainstr.size();
        int m = substr.size();
        //覆盖所有编码字符,一般256足够 
        vector<int> last_occurrence(256,-1);
        //记录子字符串最后一个出现字母的位置
        for (int i = 0; i < m; ++i) {
                last_occurrence[substr[i]] = i;
        }

        int i = 0;
        while (i <= n - m) {
                int j = 0;
                while (j < m && mainstr[i + j] == substr[j])
                        ++j;
                if (j == m) {
                        result.push_back(i);
                        i += m;
                } else {
                        //窗口超过主字符串 || 窗口的最后一位不在子字符串之中
                        if (i + m >= n || last_occurrence[mainstr[i + m]] == -1) {
                                i += m + 1;
                        }else {
                        //last_occurrence存在值,将窗口的最后一位对齐子字符串
                                i += m - last_occurrence[mainstr[i + m]];
                        }
                }
        }
        return result;
};

int main(){
        string text = "AAAABCABDAACABC";
        string sub = "ABD";
        vector<int> pos = sunday(text, sub);
        if (pos.empty())
                cout << "未找到子字符串" << endl;
        else {
                cout << "第一个出现的字符串在位置:" << pos[0] << endl;
        }
        return 0;
}

4、KMP

KMP算法和上述SUNDAY搜索算法类似都是从左到右匹配,并且通过“减枝”以减少不必要的搜索;

KMP算法使用next数组匹配相同的【前缀】和【后缀】进行“减枝”;

通过上述表述,所以KMP算法的核心在于如何求出next数组,并利用数组进行“减枝”;

#include <iostream>
#include <string.h>
#include <vector>
using namespace std;
int GetNext(string str, vector<int> & next) {
        int n = str.size();
        int j = 0;
        next[0] = 0;
        for (int i = 1; i < n; ++i) {
                while (j > 0 && str[i] != str[j]) {
                        j = next[j - 1];
                }
                if (str[i] == str[j]) ++j;
                next[i] = j;


        }

        return 0;
}

int kmp(string a, string b) {
        vector<int> vec(b.size(), 0);
        GetNext(b, vec);
        int a_size = a.size();
        int j = 0;
        for (int i = 0; i < a_size; ++i) {
                while ( j > 0 && a[i] != b[j]) {
                        j = vec[j - 1];
                }
                if (a[i] == b[j]) {
                        ++j;
                }
                if (j == b.size()) {
                        return i - j + 1;
                }
        }
        return -1;
}

int main(){
        string a = "aaaabcabcd";
        string b = "abcd";
        int i = kmp(a, b);
        cout << i << endl;

        return 0;
}

5、str.find

#include <iostream>
#include <string>
using namespace std;
int main() {
        string mainstr = "this is a simple string.";
        string substr = "sim";

        size_t found = mainstr.find(substr);
        if (string::npos != found) {
                cout << "找到子字符串,位置在:" << found << ", 子字符串是:" << mainstr.substr(found, substr.size()) << endl;
        }else {
                cout << "未找到子字符串" << endl;
        }
        return 0;
}

6、Boyer-Moore

Boyer-Moore和前文提到的方式不同点在于,他是一种从右向左比较substr和mainstr的文本算法。
方法的核心在于使用了两种预处理政策:坏字符规则和好后缀规则:
坏字符规则:当模式串和文本不匹配的时候,会查看不匹配的字符(这种字符被称为坏字符)在模式串之中的位置。如果坏字符在模式串之中不存在,则可以将模式串移动到坏字符之后;如果存在,则将模式串移动到模式串中该
字符的下一个位置。
好后缀规则:好后缀规则是在坏字符规则之后应用的。如果坏字符规则没有提供足够的信息来移动模式串,则会查找模式串与文本中已经匹配的后缀的最长后缀,并尝试将模式串移动到该后缀的下一个位置

Boyer-Moore算法的效率在于它能够根据当前的不匹配情况来决定跳过多少比较,而不是每次只移动一个位置。这使得Boyer-Moore算法在处理大型文本和模式串时非常高效。

代码实现:

//仅使用坏字符的时候,和sundaysearch相似

#include <iostream>
#include <bits/stdc++.h>
using namespace std;

vector<int> BoyerMoore(const string &main_str, const string &sub_str) {
        vector<int> result;
        int n = main_str.size();
        int m = sub_str.size();

        vector<int> badchar(256, -1);
        for (int i = 0; i < m; ++i)
                badchar[sub_str[i]] = i;

        int i = 0;
        while(i <= n - m) {
                int j = m - 1;
                while (j >= 0 && main_str[i + j] == sub_str[j])
                        --j;
                if (j < 0) {
                        result.push_back(i);
                        i += m;
                }else {
                        //坏字符规则移动
                        int shift = j - badchar[main_str[i + j]];
                        i += shift > 0? shift : 1;
                }

        }

        return result;

};


int main() {
    string text = "ABAAABCDABDABDE";
    string pattern = "ABD";
    vector<int> positions = BoyerMoore(text, pattern);

    if (positions.empty()) {
        cout << "不存在子字符串." << endl;
    } else {
        cout << "第一个子字符串位置在" << positions[0] << endl;
    }

    return 0;
}
//使用坏字符+好后缀,写的有点问题,暂时不

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值