//简单算法(又叫朴素算法),复杂度为O(mn)
int Index(SString S, SString T, int pos)
//返回子串T在主串S中第pos个字符后的位置,若不存在,
//则返回0,其中,T非空,1<pos<StrLenght(S)
{
int i = pos;
int j = 1;
while(i<=S[0] && j<=T[0]) //第0个位置存放串的长度
{
if(S[i] == T[j])
{
++i;
++j;
}
else
{
i = i-j+2;
j=1;
}
}
int Index(SString S, SString T, int pos)
//返回子串T在主串S中第pos个字符后的位置,若不存在,
//则返回0,其中,T非空,1<pos<StrLenght(S)
{
int i = pos;
int j = 1;
while(i<=S[0] && j<=T[0]) //第0个位置存放串的长度
{
if(S[i] == T[j])
{
++i;
++j;
}
else
{
i = i-j+2;
j=1;
}
}
if(j>T[0])
return i - T[0];
else
return 0;
return i - T[0];
else
return 0;
}
//KMP算法,复杂度为O(m+n)
int Index_KMP(SString S, SString T,int pos)
{
int i = pos;
int j = 1;
while(i<=S[0] && j<=T[0]) //第0个位置存放串的长度
{
if(j==0 || S[i]==T[j])
{
++i;
++j;
}
else
{
j = next[j];
}
}
int Index_KMP(SString S, SString T,int pos)
{
int i = pos;
int j = 1;
while(i<=S[0] && j<=T[0]) //第0个位置存放串的长度
{
if(j==0 || S[i]==T[j])
{
++i;
++j;
}
else
{
j = next[j];
}
}
if(j>T[0])
return i - T[0];
else
return 0;
return i - T[0];
else
return 0;
}
//next值的算法
void get_next(SString &T, int next[])
//求模式串T的next函数值并存入数组next.
{
int i =1;
next[1] = 0;
int j = 0;
while(i < T[0])
{
if(j==0 || T[i] == T[j])
{
++i;
++j;
next[i] = j;
}
else
j= next[j];
}
}
void get_next(SString &T, int next[])
//求模式串T的next函数值并存入数组next.
{
int i =1;
next[1] = 0;
int j = 0;
while(i < T[0])
{
if(j==0 || T[i] == T[j])
{
++i;
++j;
next[i] = j;
}
else
j= next[j];
}
}
//next值的改进算法
void get_nextval(SString &T, int nextval[])
//求模式串T的next函数值并存入数组next.
{
int i =1;
next[1] = 0;
int j = 0;
while(i < T[0])
{
if(j==0 || T[i] == T[j])
{
++i;
++j;
if(T[i]!=T[j])
nextval[i] = j;
else
nextval[i]=nextval[j];
}
else
j= next[j];
}
}
void get_nextval(SString &T, int nextval[])
//求模式串T的next函数值并存入数组next.
{
int i =1;
next[1] = 0;
int j = 0;
while(i < T[0])
{
if(j==0 || T[i] == T[j])
{
++i;
++j;
if(T[i]!=T[j])
nextval[i] = j;
else
nextval[i]=nextval[j];
}
else
j= next[j];
}
}
转载于:https://blog.51cto.com/didiw8899/105637