1.Brute-Force算法(暴力算法)
int BF(SqSting s, SqString t)
{
int i = 0, j = 0;
while (i < s.length && j < t.length)
{
if (s.data[i] == t.data[j])
{
i++;
j++;
}
else
{
i = i - j + 1;
j = 0;
}
}
if (j >= t.length)
return (i - t.length);
else
return (-1);
}
2.KMP - Next数组
void GetNext(SqString t, int next[])
{
int j, k;
j = 0;
k = -1;
next[0] = -1;
while (j < t.length - 1)
{
if (k == -1 || t.data[j] == t.data[k])
{
j++;
k++;
next[j] = k;
}
else
k = next[k];
}
}
int KMPIndex(SqString s, SqString t)
{
int next[MAXSIZE], i = 0, j = 0;
GetNext(t, next);
while (i < s.length && j < t.length)
{
if (j == -1 || s.data[i] == t.data[j])
{
i++;
j++;
}
else
j = next[j];
}
if (j >= t.length)
return (i - t.length);
else
return (-1);
}
3.KMP - NextVal数组
void GetNextVal(SqString t, int nextval[])
{
int j, k;
j = 0;
k = -1;
nextval[0] = -1;
while (j < t.length)
{
if (k == -1 || t.data[j] == t.data[k])
{
j++;
k++;
if (t.data[j] != t.data[k])
nextval[j] = k;
else
nextval[j] = nextval[k];
}
else
k = nextval[k];
}
}
int KMPIndex(SqString s, SqString t)
{
int nextval[MAXSIZE], i = 0, j = 0;
GetNextVal(t, nextval);
while (i < s.length && j < t.length)
{
if (j == -1 || s.data[i] == t.data[j])
{
i++;
j++;
}
else
j = nextval[j];
}
if (j >= t.length)
return (i - t.length);
else
return (-1);
}