KMP算法

如果用 Brute-Force算法  

KMP算法

K:字符前的K个字符和字串的头K个字符相等 1.k=-1 只有模式串的第一个字符的k值为-1

2.K>0 表示指定字符前面k个字符和模式串的头k个字符相等
3.K=0 其他情况。(模式串第2个字符的k值必为0.)

例:

c下面对应2,表示C前面有两个 字符串相等,回溯的时候,回溯到第三个字符串就可以了

再看一段代码..

 public static void GetNext(string t,int[] next)
        {
            int k = -1, j = 0;

            next[0] = -1;
            while (j<t.Length-1)
            {
                if (k==-1 || t[j]==t[k]) 
                {
                    j++;
                    k++;
                    next[j] = k;
                }
                else
                {
                    k = next[k];
                }
            }
        }

 

全不代码!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication11
{
    class Program
    {
        static void Main(string[] args)
        {
           


            Console.WriteLine(KMPIndex("abadababc","ababc").ToString());
            
            
            Console.ReadLine();

            //结果等于4


        }


        static int KMPIndex(string s, string t)
        {
            int[] patt=new int[t.Length];




            int i = 0, j = 0, v;


            next.GetNext(t, patt);


            while (i<s.Length&&j<t.Length)//正在匹配
            {
                if (j==-1 || s[i]==t[j])
                {
                    i++;
                    j++;
                }
                else
                {
                    j = patt[j];
                }
            }
            if (j>=t.Length)//匹配成功
            {
                v = i - t.Length;

            }
            else
            {
                v = -1;
            }
            return v;  
        }
    }


    class next
    {
        public static void GetNext(string t, int[] next)
        {
            int k = -1, j = 0;

            next[0] = -1;
            while (j < t.Length - 1)
            {
                if (k == -1 || t[j] == t[k])
                {
                    j++;
                    k++;
                    next[j] = k;
                }
                else
                {
                    k = next[k];
                }
            }
        }
    }

}

 

 

 

 

posted @ 2014-07-06 07:26  欢呼雀跃  阅读(163)  评论(0)    收藏  举报