数据结构与算法分析-Chapter4

Chapter4-串

4.1 串类型的定义

        n(n≥0)个字符的有限序列:
s = “ a 1 , a 2 , a 3 , . . . , a n ” s = “a_1, a_2,a_3,...,a_n” s=a1a2a3...an
其中,s称之为串名, a i a_i ai称之为串值,n为串长。

        串包括了空串,字串和主串。
在这里插入图片描述
**需要注意的是:**字串中的每一个元素的位置与原本的串中的位置相同且相邻。

4.2 字符串模式匹配算法

4.2.1 暴力匹配

        顾名思义,在匹配时非常暴力。时间复杂度极高。不在此多赘述。

4.2.2 KMP算法

        这里直接找了B站上的一个博主介绍KMP算法。

最浅显易懂的 KMP 算法讲解


        对于KMP算法主要考察的是next数组的求解,在这里用Kimi生成了个求解next数组并打印出next数组的代码供学习印证。

#include <iostream>
#include <vector>
#include <string>

// 计算next数组的函数
std::vector<int> computeNext(const std::string& pattern) {
    int m = pattern.length();
    std::vector<int> next(m, 0);
    int j = 0;
    for (int i = 1; i < m; i++) {
        while (j > 0 && pattern[i] != pattern[j]) {
            j = next[j - 1];
        }
        if (pattern[i] == pattern[j]) {
            j++;
        }
        next[i] = j;
    }
    return next;
}

int main() {
	while (true)
	{
		std::string pattern;
    	std::cout << "Enter the pattern: ";
    	std::getline(std::cin, pattern);

    	std::vector<int> next = computeNext(pattern);
     	for (int i = 0; i < next.size(); ++i) {
        	std::cout << pattern[i] << " ";
    	}
    	std::cout << std::endl;
    	for (int i = 0; i < next.size(); ++i) {
        	std::cout << next[i] << " ";
    	}
    	std::cout << std::endl;
	}
    

    return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值