因为在做大文件上传的分析中需要用到一段字符串的匹配算法,所以重新学习了一次KMP算法.
private int[] GetNextVal(string t)
{
int j = 0, k = -1;
int[] nextVal = new int[t.Length];
nextVal[0] = -1;
while (j < t.Length-1)
{
if (k == -1 || t[j] == t[k])
{
j++;
k++;
if (t[j] != t[k])
{
nextVal[j] = k;
}
else
{
nextVal[j] = nextVal[k];
}
}
else
{
k = nextVal[k];
}
}
return nextVal;
}
{
int j = 0, k = -1;
int[] nextVal = new int[t.Length];
nextVal[0] = -1;
while (j < t.Length-1)
{
if (k == -1 || t[j] == t[k])
{
j++;
k++;
if (t[j] != t[k])
{
nextVal[j] = k;
}
else
{
nextVal[j] = nextVal[k];
}
}
else
{
k = nextVal[k];
}
}
return nextVal;
}
private int KmpIndexOf(string s, string t)
{
int i = 0, j = 0, v;
int[] nextVal = GetNextVal(t);
while (i < s.Length && j < t.Length)
{
if (j == -1 || s[i] == t[j])
{
i++;
j++;
}
else
{
j = nextVal[j];
}
}
if (j >= t.Length)
v = i - t.Length;
else
v = -1;
return v;
}
{
int i = 0, j = 0, v;
int[] nextVal = GetNextVal(t);
while (i < s.Length && j < t.Length)
{
if (j == -1 || s[i] == t[j])
{
i++;
j++;
}
else
{
j = nextVal[j];
}
}
if (j >= t.Length)
v = i - t.Length;
else
v = -1;
return v;
}