C# Knuth-Morris-Pratt算法的实现
我正在尝试实现KMP算法。部分“if(W[i]==S[m+i])返回索引超出范围异常,我无法使其工作 我在维基百科上举了一个例子:C# Knuth-Morris-Pratt算法的实现,c#,algorithm,C#,Algorithm,我正在尝试实现KMP算法。部分“if(W[i]==S[m+i])返回索引超出范围异常,我无法使其工作 我在维基百科上举了一个例子: static int[]KMPTable(字符串W) { int[]T=新的int[W.Length]; int pos=2; int cnd=0; T[0]=-1; T[1]=0; 而(位置0) { cnd=T[cnd]; } 其他的 { T[pos]=0; pos=pos+1; } } 返回T; } 静态int[]KMPSearch(字符串S、字符串W) { i
static int[]KMPTable(字符串W)
{
int[]T=新的int[W.Length];
int pos=2;
int cnd=0;
T[0]=-1;
T[1]=0;
而(位置0)
{
cnd=T[cnd];
}
其他的
{
T[pos]=0;
pos=pos+1;
}
}
返回T;
}
静态int[]KMPSearch(字符串S、字符串W)
{
int m=0;
int i=0;
int[]kmpNext=KMPTable;
列表结果=新列表();
而(m+i-1)
i=kmpNext[i];
其他的
i=0;
}
}
返回result.ToArray();
}
当m+istatic int[] KMPTable(string W)
{
int[] T = new int[W.Length];
int pos = 2;
int cnd = 0;
T[0] = -1;
T[1] = 0;
while (pos < W.Length)
{
if (W[pos - 1] == W[cnd])
{
T[pos] = cnd + 1;
cnd = cnd + 1;
pos = pos + 1;
}
else
if (cnd > 0)
{
cnd = T[cnd];
}
else
{
T[pos] = 0;
pos = pos + 1;
}
}
return T;
}
static int[] KMPSearch(string S, string W)
{
int m = 0;
int i = 0;
int[] kmpNext = KMPTable(S);
List<int> result = new List<int>();
while (m + i < S.Length)
{
if (W[i] == S[m + i])
{
if (i == W.Length - 1)
{
result.Add(m);
}
i = i + 1;
}
else
{
m = m + i - kmpNext[i];
if (kmpNext[i] > -1)
i = kmpNext[i];
else
i = 0;
}
}
return result.ToArray();
}