呵呵  大家可以把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;
        }
    }


 

posted on 2010-03-25 09:39  feathersky  阅读(535)  评论(2编辑  收藏  举报