KMP算法 —— 知识点

class KMP{

string pattern;

int len ;

vector next; // 这里的next数组是从1开始的

// 也叫失配数组,next[i] 表示以第i位结尾的子串与模式串的前缀相同的最大长度(但不能是自身),也就是所谓的最长公共前后缀

void Next(){

next.resize(len+1);

int j = 0;

for(int i = 2; i <= len; i++) {

while(j > 0 && pattern[i] != pattern[j + 1]) {

j = next[j];

}

if(pattern[i] == pattern[j + 1]) {

j++;

}

next[i] = j;

}

}

public:

KMP(const string &pattern) {

len = pattern.size();

this->pattern = " " + pattern;

Next();

}

bool isSubstringOfText(const string& text) {

return getPositions(text).size() > 0;

}

// 统计模式串在文本串出现的次数

int getTimes(const string& text) {

return getPositions(text).size();

}

// 统计模式串在文本串的出现的次数

vector getPositions(const string& text) {

vector res;

if(text.size() < len) return res;

int j = 0;

for(int i = 0; i < text.size(); i++){

while (j > 0 && text[i] != pattern[j + 1]){

j = next[j];

}

if(text[i] == pattern[j + 1]){

j++;

}

if(j == len){

// i 是匹配时文本串的位置(从0开始)

res.push_back(i);

j = next[j];

}

}

re 《一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义》无偿开源 威信搜索公众号【编程进阶路】 turn res;

};

// 求数组f[] 其中 f[i] 表示文本串以i结尾的子串与 pattern 串的前缀相同的最大长度(这里也是从1开始计数)

vector getFArray(const string& text) {

int m = text.size(), j = 0;

vector f(m+1);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值