KMP及next数组实现代码
2018-01-31 16:59
120 查看
next数组求解:
以1开始,next[1]=0,next[2]=1,next:将前面n-1个字符,计算从首尾开始组成最大的相同子串的长度,如果找到,那么next值是该长度加1,否则next值是1。
void getNext(char *p,int *next) { int j,k; next[1]=0; j=1; k=0; while(j<strlen(p)-1) { if(k==0||p[j]==p[k]) //匹配的情况下,p[j]==p[k],next[j+1]=k+1; { j++; k++; next[j]=k; } else //p[j]!=p[k],k=next[k] k=next[k]; } }
KMP实现:
#include <iostream> #include <vector> #include <string> using namespace std; int KMP(string S, string T) { vector<int> next = getNext(T); int i = 1, j = 1; while (S[i] != '\0' && T[j] != '\0') { if ( j==0 || S[i] == T[j]) { ++i; ++j; } else { j = next[j]; } } if (T[j] == '\0') return i - j + 1; else return 0; } int main() { string S = "ababaababcb"; string T = "ababc"; int num = KMP(S, T); cout << num; return 0; }
相关文章推荐
- Next数组的实现步骤与代码,以及三个简单应用(包含KMP)
- KMP模式匹配算法原理分析、next数组优化及java实现
- KMP_next数组_while详解_Java实现
- KMP算法中NEXT数组的作用以及代码实现
- 计算KMP模式匹配算法中next数组的代码分析及改进型KMP算法中nextval数组代码分析
- KMP的创造next数组代码及常用的字符串比较代码
- KMP算法的next、next value数组代码实现及POJ3461
- KMP算法与next数组的代码初步实现
- 雇佣问题随机排列数组(permuteBySorting)-c++代码实现及运行实例结果
- 雇佣问题原址排列给定数组(randomize In Place)-c++代码实现及运行实例结果
- poj2185Milking Grid【kmp next数组求循环节】
- 寻找数组中第二大的数_代码实现
- nyoj 2340 最小循环节(KMP之next数组的应用)
- hdu 1358 Period(KMP之next数组)
- php对数组排序实现代码
- Python自定义类的数组排序实现代码
- 自己实现了一下C++STL中的next_permutation,名为ant_next_permutation,发下代码
- kmp的next数组的运用(求字符串的最小循环节)
- openssl对数组加密解密的完整实现代码
- POJ 2752 Seek the Name, Seek the Fame(KMP next数组应用)