//KMP匹配方法
public int Index(StringList T, int pos = 1) {
if (this.isEmpty() || T.isEmpty()) {
return 0;
}
int mainLength = this.Length();
int matchLength = T.Length();
int i = 1;
int j = 0;
if (pos > 0 && pos <= mainLength) {
i = pos;
int[] nextval = new int[matchLength + 1];
this.getNextval(T, nextval);
for (; i <= mainLength; i++)
{
while (j > 0 && this[i] != T[j + 1])
{
j = nextval[j];
}
if (this[i] == T[j + 1])
{
j++;
}
if (j == matchLength)
{
return i - matchLength + 1;
}
}
}
return 0;
}和计算nextvalue数组的方法差不多,就是使用两个指标,主串指标和匹配串指标,将主串指标位置的字符和匹配串指标位置的字符对比,如果相同,就都往后移动一位,如果不相同,匹配串就根据nextvalue的数组回到合适的位置再和主串对比。