BM算法

本文介绍了一种高效的字符串匹配算法——Boyer-Moore算法,并提供了详细的C#实现代码。该算法通过预处理模式串生成bad character rule和good suffix rule两个跳转表来加速搜索过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

namespace ConsoleApplication1
{
    class Program
    {

        static int BmSerach(byte[] source, byte[] template)
        {
            // Prepare BmBc
            int[] bmBc = new int[256];
            for (int i = 0; i < bmBc.Length; ++i)
                bmBc[i] = template.Length;
            for (int i = 0; i < template.Length - 1; ++i)
                bmBc[template[i]] = template.Length - 1 - i;

            // Prepare Suffix
            int[] suff = new int[template.Length];
            suff[suff.Length - 1] = template.Length;
            for (int i = template.Length - 2; i >= 0; --i)
            {
                int q = i;
                while (q >= 0 && template[q] == template[template.Length - 1 - (i - q)])
                    --q;
                suff[i] = i - q;
            }

            // Prepare BmGs
            int[] bmGs = new int[template.Length];
            for (int i = 0; i < bmGs.Length - 1; i++)
                bmGs[i] = template.Length;
            int j = 0;
            for (int i = template.Length - 1; i >= 0; --i)
                if (suff[i] == i + 1)
                    for (; j < template.Length - 1 - i; ++j)
                        if (bmGs[j] == template.Length)
                            bmGs[j] = template.Length - 1 - i;
            for (int i = 0; i <= template.Length - 2; ++i)
                bmGs[template.Length - 1 - suff[i]] = template.Length - 1 - i;
            bmGs.ToList().ForEach(x => Console.Write(x.ToString() + ' '));
            //Trace.WriteLine("");

            // Search
            j = 0;
            while (j < source.Length - template.Length)
            {
                int i = template.Length - 1;
                for (; i >= 0 && template[i] == source[j + i]; i--) ;
                if (i < 0)
                    return j;
                else
                {
                    int step = Math.Max(bmBc[source[j + i]], bmGs[i]);
                    j += step;
                    Console.WriteLine("STEP:" + j);
                }
            }
            return -1;
        }

        static void Main(string[] args)
        {
        loop:
            Console.WriteLine("输入文本字符串:");
            string a = Console.ReadLine();
            Console.WriteLine("输入模板:");
            string b = Console.ReadLine();
            int i = BmSerach(Encoding.ASCII.GetBytes(a), Encoding.ASCII.GetBytes(b));
            Console.WriteLine(i);
            goto loop;
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值