基本信息
源码名称:KMP算法C++实现
源码大小:1.15KB
文件格式:.cpp
开发语言:C/C++
更新时间:2021-04-08
友情提示:(无需注册或充值,赞助后即可获取资源下载链接)
嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):813200300
本次赞助数额为: 2 元×
微信扫码支付:2 元
×
请留下您的邮箱,我们将在2小时内将文件发到您的邮箱
源码介绍
KMP算法是一种改进的字符串匹配算法,时间复杂度为O(m n)
KMP算法是一种改进的字符串匹配算法,时间复杂度为O(m n)
#include <iostream> #include <cstring> using namespace std; void buildNext(char* pat, int* next){ int len = strlen(pat); next[0] = 0; int now = 0; int i = 1; while (i < len) { if (pat[now] == pat[i]) { now ; next[i] = now; i ; } else if (now == 0) { next[i] = 0; i ; } else { now = next[now-1]; } } } int search(char* str, char* pat, int* next){ int strLen = strlen(str); int patLen = strlen(pat); int tar = 0; int pos = 0; while (tar < strLen) { if (str[tar] == pat[pos]) { tar ; pos ; } else if (pos != 0) { pos = next[pos-1]; } else if (pos == 0) { tar ; } if (pos == patLen) return tar - pos; } return -1;//不存在匹配子串 } int main() { char str[10000]; char pat[100]; int next[100]; cin >> str >> pat; buildNext(pat,next); cout << search(str,pat,next) << endl; return 0; }
#include <iostream>