呵呵 大家可以把matchCount 替换成next 我是为了讲解方便 写成matchCount 呵呵
代码
public static List<int> Match(string content, string pattern) //返回匹配的位置
{
int[] matchCount = Next(pattern);
List<int> matchPosition = new List<int>();
int j=-1;
for (int i = 0; i < content.Length; i++)
{
while ( (content[i] != pattern[j + 1])&&(j>0)) j = matchCount[j];
if(content[i]==pattern[j+1]) j=j+1;
if (j == pattern.Length-1)
{
matchPosition.Add(i-pattern.Length+1);
j = matchCount[j];
}
}
return matchPosition;
}
public static int[] Next(string s)
{
int[] matchCount = new int[s.Length];
int j = 0;
matchCount[1] = 0;
for (int i = 2; i < s.Length; i++)
{
while ((s[i] != s[j+1])&&(j>0)) j = matchCount[j];
if (s[i] == s[j + 1]) j = j + 1;
matchCount[i] = j;
}
return matchCount;
}
}
{
int[] matchCount = Next(pattern);
List<int> matchPosition = new List<int>();
int j=-1;
for (int i = 0; i < content.Length; i++)
{
while ( (content[i] != pattern[j + 1])&&(j>0)) j = matchCount[j];
if(content[i]==pattern[j+1]) j=j+1;
if (j == pattern.Length-1)
{
matchPosition.Add(i-pattern.Length+1);
j = matchCount[j];
}
}
return matchPosition;
}
public static int[] Next(string s)
{
int[] matchCount = new int[s.Length];
int j = 0;
matchCount[1] = 0;
for (int i = 2; i < s.Length; i++)
{
while ((s[i] != s[j+1])&&(j>0)) j = matchCount[j];
if (s[i] == s[j + 1]) j = j + 1;
matchCount[i] = j;
}
return matchCount;
}
}