KMP算法实现(C#)

博客中代码都经过运行并且没有bug

//返回模式字符串对应的next值
static int[] Next(string T)
{
  //string str = "aaaab";//"ababcabababc";
  int[] next = new int[T.Length];

  //指引被对比字符串
  int i = 0;

  //指引模式字符串
  int j = -1;

  next[0] = -1;

  while (i < T.Length - 1)
  {
    if (j == -1 || T[i] == T[j])
    {
      i++;
      j++;

      if (i > 0)
      {
        next[i] = j;
      }
    }
    else
    {
      j = next[j];
    }
  }
	//优化next数组
  for (int m = 0; m < next.Length; m++)
  {
    int k = next[m];
    if (next[m] == -1)
      continue;

    if (T[m] == T[k])
    {
      next[m] = next[k];
    }
  }
  
  return next;
}

//KMP算法本体
private static int KMP(string S,string T)
{
  //string S = "ababcabcaabcbaabc";
  //string strT = "cabc";//"ababcabababc";
  int[] next = Next(T);

  //指引被对比字符串
  int i = 0;

  //指引模式字符串
  int j = -1;
  

  while (i < S.Length)
  {
    if (j == -1 || S[i] == T[j])
    {
      i++;
      j++;

      if (j > T.Length - 1)
      {
        return i-j;
      }
    }
    else
    {
      j = next[j];
    }
  }

  return -1;
}



static void Main(string[] args)
{
  //int[] nextMain = Next();
  //foreach (int temp in nextMain)
  //{
  //  Console.Write(temp + " ");
  //}
  //Console.ReadKey();

  Console.WriteLine(KMP("ababcabcaabcbaabc", "cabc"));

  Console.ReadKey();
}

next()函数的意义:
1.找到模式字符串的当前字符前有几个字符与模式字符串开头字符相同

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值