#define MAXLEN 20
typedef struct {
char ch[MAXLEN];
int length;
}SString;
//求子串
bool SubString(SString &Sub, SString S, int pos, int len) {
if (pos + len + 1 > S.length)
return false;
for (int i = pos;i < pos + len;i++) {
Sub.ch[i - pos + 1] = S.ch[i];
}
Sub.length = len;
return true;
}
//比较两串
int StrCompare(SString S, SString T) {
for (int i = 1;i <= S.length&&i <= T.length;i++) {
if (S.ch[i] != T.ch[i])
return S.ch[i] - T.ch[i];
}
return S.length - T.length;
}
//朴素的模式匹配定位操作
int Index(SString S, SString T) {
int i = 1,j = 1;//i为主串,j为模式串上的
while (i <= S.length&&j <= T.length) {
if(S.ch[i]==T.ch[j])
{
++i;
++j;
}
else {
i = i - j + 2;
j = 1;
}
}
if (j > T.length)
return i - T.length;
else
return 0;
}
//KMP算法
int Index_KMP(SString S, SString T, int next[]) {
int i = 1,j = 1;
while (i <= S.length&&j <= T.length) {
if (j == 0 || S.ch[i] == T.ch[j]) {
++i;
++j;
}
else {
j = next[j];
}
}
if (j > T.length)
return i - T.length;
else
return 0;
}
//KMP优化后的
void get_nextval(SString T, int nextval[]) {
int i = 1, j = 0;
nextval[1] = 0;
while (i < T.length) {
if (j == 0 || T.ch[i] == T.ch[j]) {
++i;++j;
if (T.ch[i] != T.ch[j])
nextval[i] = j;
else
nextval[i] = nextval[j];
}
else
j = nextval[j];
}
}