KMP模式匹配

来源:互联网 发布:java小写字母转大写 编辑:程序博客网 时间:2024/06/10 09:51
#include<iostream>using namespace std;int strlen(char* S){int i = 0;int counter = 0;while (S[i] != '\0') {i++;counter++;}return counter;}void get_next(char* T, int *next){int i =0,j = -1;next[0] = -1;while (T[i]!='\0') {if (j==-1 || T[i] == T[j]) {i++;j++;next[i] = j;}elsej = next[j];}}int index_KMP(char* S, char* T, int pos){int i = pos-1;int j = 0;int next[255];get_next(T, next);while (i<strlen(S) && j<strlen(T)) {//注意这里千万不能写成T[i]!='\0' && S[j]!='\0'if (j == -1 || S[i] == T[j]) {i++;j++;}elsej = next[j];}cout << "i= " << i << endl;cout << "j= " << j << endl;if (T[j] == '\0')return i - j + 1;elsereturn 0;}void get_nextval(char* T, int *nextval){int i = 0, j = -1;nextval[0] = -1;while (T[i] != '\0') {if (j == -1 || T[i] == T[j]){i++;j++;if (T[i] != T[j])nextval[i] = j;elsenextval[i] = nextval[j];}elsej = nextval[j];}}int main(){int next[255];char* S = "aaabbbaaabbb";char* T = "bbb";cout << index_KMP(S, T, 5)<< endl;system("pause");return 0;}

1 0