KMP之C#实现

3 篇文章 0 订阅

关于KMP的讲解请参考上篇《三步学通KMP》(https://blog.csdn.net/helloworldchina/article/details/104465772),这里笔者仅补充一下C#代码的实现,见下:
1 next[]数组代码:

public static int[] kmpNext(String str)
{
    int[] next = new int[str.Length];
    next[0] = 0;
    for (int j = 1, k = 0; j < str.Length; j++)
    {
        while (k > 0 && str[k] != str[j])
        {
            k = next[k - 1];
        }
        if (str[j] == str[k])
        {
            k++;
        }
        next[j] = k;
    }
    return next;
}

2 KMP代码

public static int kmp(String s, String t, int[] next)  //主串  t 模式串
{
   for (int i = 0, j = 0; i < s.Length; i++)
   {

       while (j > 0 && s[i] != t[j])
       {
           j = next[j - 1];    //下一个匹配位为next数组的第j-1位
       }
       if (s[i] == t[j])
       {
           j++;//主串通过i进行加1,模式串通过j加1
       }
       if (j == t.Length)
       {
           return i - j + 1;//返回匹配位置
       }
   }
   return -1;
}

3 打印next[]数组代码

public static void printNext(String s)
{
    Console.WriteLine("********************");
    int[] nextI = kmpNext(s);
    Console.Write("模式串:'" + s + "'的next[]数组为:[");
    for (int i = 0; i < (nextI.Length); i++)
    {
        Console.Write(nextI[i] + " ");
    }
    Console.Write("]");
    Console.WriteLine();
    Console.WriteLine("模式串长度为:" + nextI.Length);
}

4 主函数代码

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

public static void Main(string[] args)
{
    String s = "CDFGFABABAFABABAAAQWEDC";
    String t = "ABABAA";
    int[] next = kmpNext(t);
    int res = kmp(s, t, next);
    if (res != -1)
    {
        Console.WriteLine("起始位置为:" + res);
    }
    else Console.WriteLine("主串中不包含字符串:" + t);
    printNext("ABCDABD");
    printNext("ABABAA");
    printNext("ABAABCAC");
    Console.ReadLine();
}

5运行结果
在这里插入图片描述

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值