KMP字符串快速匹配

求回溯串

static int [] GetNextVal(string str)
        {
	    int [] next= new int [str.length];
            int i = 0;
            int j = -1;
            next[0] = -1;
            while (i < str.Length - 1)
            {
                if (j == -1 || str[i] == str[j])
                {
                    i++;
                    j++;
                    next[i] = j;
                }
                else
                {
                    j = next[j];
                }
            }
	    return next;
}

  KMP算法

 static int KMP(string zstr, string mstr)
        {
            int i, j;
            int[] next = new int[mstr.Length];
            next= GetNextVal(mstr);
            i = 0;
            j = 0;
            while (i < zstr.Length && j < mstr.Length)
            {
                if (j == -1 || zstr[i] == mstr[j])
                {
                    ++i;
                    ++j;
                }
                else
                {
                    j = next[j];
                }
            }
            if (j == mstr.Length)
                return i - mstr.Length;
            return -1;
        }

  

posted @ 2013-04-24 20:49  冯际成  阅读(98)  评论(0)    收藏  举报

返回顶部