/**
* author:lingd
* date:2013-12-5
*/
#include<stdio.h>
#include<string.h>
#define String char*
void get_next(String ,int* );
int str_pos(String ,String ,int );
void get_nextval(String T,int* next);
int main(void){
int next[100],len,i;
String s = "ababababdcabababababdc";
String t = "abababc";
printf("%d",str_pos(s,t,0));
return 0;
}
void get_next(String T,int* next){
int j,i,lenT;
j = -1;
i = 0;
lenT = strlen(T);
next[0] = -1;
while(i < lenT){
if(j == -1 || T[j] == T[i]){ //i是后缀 j是前缀
i++;
j++;
next[i] = j;
}else{
j = next[j];
}
}
}
//改进
void get_nextval(String T,int* next){
int j,i,lenT;
j = -1;
i = 0;
lenT = strlen(T);
next[0] = -1;
while(i < lenT){
if(j == -1 || T[j] == T[i]){ //i是后缀 j是前缀
i++;
j++;
if(T[j] != T[i]){
next[i] = j;
}else{
next[i] = next[j];
}
}else{
j = next[j];
}
}
}
/**
S主串
T子串
pos 开始匹配的子串起始位置
return 位置 or -1(无匹配)
*/
int str_pos(String S,String T ,int pos){
int lenS,lenT,i,j;
int next[255];
lenS = strlen(S);
lenT = strlen(T);
i = pos;
j = 0;
//get_next(T,next); //改进前
get_nextval(T,next); //改进后
while(i < lenS && j < lenT){
if(j == -1 || T[j] == S[i]){
i++;
j++;
}else{
j = next[j]; //回朔j
}
}
//有匹配
if(j >= lenT){
return i - lenT;
}
return -1; //没有匹配
}
/*
0 1 2 3 4 5 6
a b a b a b c
-1 0 0 1 2 3 4 //改进前的next
-1 0-1 0-1 0 4 //改进后的next
*/