news 2026/6/23 19:48:22

kmp算法

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
kmp算法

kmp算法运用于字符串匹配,具体实现过程如下:

拿从母串中找是否存在某个字串举例

1.求字串的next数组,什么是next数组,即每个字母所在位置对应的最长相等前后缀,例如abcabf的next数组就是000120,那如何找一个next数组呢

void getnext(int next[], char* s) { int len_ = strlen(s);//求出字符串长度 int j = 0; next[0] = 0; for (int i = 1; i < len_; i++) { while (j > 0 && s[j] != s[i]) { j = next[j - 1];//回退 } if (s[j] == s[i]) { j++; } next[i] = j; } }

首先,我们将next首元素赋值为0,j是前缀指针,i是后缀指针,i一直向后移动,只有当i和j指向元素是相同的时候,j才向后移动。一旦不相等,j就一直回退,一种可能是到相等位置,一种可能一直找不到相等的,回到首元素位置。要注意的是,j不仅是前缀指针,它同时也是每个元素对应的next

2.将子串和母串进行比对

i指向母串,一直向后移动,j指向子串,从遇到相等的开始,j也开始移动。一旦不相等,j就开始回退,也是两种情况一种可能是到相等位置,一种可能一直找不到相等的,回到首元素位置。一旦j移动到元素末尾,即表示存在

bool judge(char* a, char* b,int next[]) { int j = 0;//这是字串 int i = 0;//这是母串 int len1 = strlen(a); int len2 = strlen(b); for (i = 0; i < len2; i++) { while (j > 0 && a[j] != b[i]) { j = next[j - 1];//回退 } if (a[j] == b[i]) { j++; } if (j == len1) { return true; } } if (j != len1) { return false; } return 0; }

这是全部实现过程,如有错误,请指出

void getnext(int next[], char* s) { int len_ = strlen(s);//求出字符串长度 int j = 0; next[0] = 0; for (int i = 1; i < len_; i++) { while (j > 0 && s[j] != s[i]) { j = next[j - 1];//回退 } if (s[j] == s[i]) { j++; } next[i] = j; } } bool judge(char* a, char* b,int next[]) { int j = 0;//这是字串 int i = 0;//这是母串 int len1 = strlen(a); int len2 = strlen(b); for (i = 0; i < len2; i++) { while (j > 0 && a[j] != b[i]) { j = next[j - 1];//回退 } if (a[j] == b[i]) { j++; } if (j == len1) { return true; } } if (j != len1) { return false; } return 0; } int main() { char str1[100];//子串 char str2[200];//母串 int next[101]; scanf("%s%s", str1, str2); getnext(next, str1); bool res = judge(str1, str2,next); printf("%s", res ? "true" : "false"); return 0; }
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/6/23 19:48:48

AgentHub更新:LangGraph+千问实现Adaptive RAG系统

在大模型时代&#xff0c;如何让 AI 系统更准确、更高效地回答用户问题&#xff0c;是开发者和研究者共同关注的核心议题。传统的 RAG&#xff08;Retrieval-Augmented Generation&#xff0c;检索增强生成&#xff09; 技术虽然显著提升了模型的事实准确性&#xff0c;但在面对…

作者头像 李华
网站建设 2026/6/23 13:30:19

Steamless终极指南:轻松移除Steam游戏DRM保护

Steamless终极指南&#xff1a;轻松移除Steam游戏DRM保护 【免费下载链接】Steamless Steamless is a DRM remover of the SteamStub variants. The goal of Steamless is to make a single solution for unpacking all Steam DRM-packed files. Steamless aims to support as …

作者头像 李华
网站建设 2026/6/23 19:08:37

图像对比工具在网络安全配置中的高效应用与优化策略

图像对比工具在网络安全配置中的高效应用与优化策略 【免费下载链接】image-compare-viewer Compare before and after images, for grading and other retouching for instance. Vanilla JS, zero dependencies. 项目地址: https://gitcode.com/gh_mirrors/im/image-compare…

作者头像 李华
网站建设 2026/6/23 20:26:18

终极指南:macOS iSCSI Initiator快速连接远程存储

终极指南&#xff1a;macOS iSCSI Initiator快速连接远程存储 【免费下载链接】iSCSIInitiator iSCSI Initiator for macOS 项目地址: https://gitcode.com/gh_mirrors/is/iSCSIInitiator macOS iSCSI Initiator是一款功能强大的开源软件&#xff0c;专门为苹果电脑用户…

作者头像 李华