【小算法】KMP字符串匹配算法实现
2013-08-28 18:02
447 查看
只贴代码,具体的思想百度百科中有。
#include <stdio.h> #include <string.h> void getNext(const char *str, int *next) { int i = 0; int j = -1; int len = strlen(str); next[0] = -1; while(i < len - 1) { if(j == -1 || str[i] == str[j]) { i++; j++; next[i] = j; } else { j = next[j]; } } } int KMP_match(const char *mainStr, const char *subStr) { int mLen = strlen(mainStr); int sLen = strlen(subStr); int i = 0; int j = 0; int *pNext = NULL; pNext = (int *)malloc(sLen*sizeof(int)); getNext(subStr, pNext); while (i < mLen && j < sLen) { if (j == -1 || mainStr[i] == subStr[j]) { i++; j++; } else { j = pNext[j]; } } free(pNext); if (j == sLen) { return (i - j + 1); } return -1; } int main() { char *str1 = "afasdfasdfjowerpopnmvhn;asf"; char *str2 = "pop"; printf("match = %d\n", KMP_match(str1, str2)); return 0; }
相关文章推荐
- 算法 字符串匹配算法(朴素模式及KMP模式) java实现
- Java实现算法导论中KMP字符串匹配算法
- KMP算法基本思想与实现
- KMP模式匹配算法分析与实现
- 数据结构编程笔记十一:第四章 串 定长顺序串以及模式匹配算法(BF和KMP)的实现
- C++ 实现搜索子串KMP 算法
- 9.KMP模式匹配算法实现o(n)复杂度的匹配
- KMP匹配算法实现详解
- 算法导论-第32章-字符串匹配:Knuth-Morris-Pratt(KMP)算法C++实现
- [算法] kmp实现
- Knuth Morris Pratt (KMP)算法的证明及实现代码
- KMP字符串模式匹配算法实现
- 经典算法教程:KMP字符串匹配算法
- KMP模式匹配算法 C++实现
- 模式匹配 -- KMP 算法原理与实现
- 算法-KMP字符串匹配算法
- 【算法题】字符串匹配算法KMP
- C++实现Kmp字符匹配算法的优化版
- KMP算法之JS实现
- Java KMP匹配算法的实现