C#,字符串匹配(模式搜索)AC(Aho Corasick)算法的源代码

news2024/9/27 19:27:23

Aho-Corasick算法简称AC算法,也称为AC自动机(Aho-Corasick)算法,1975年产生于贝尔实验室The Bell Labs,是一种用于解决多模式字符串匹配的经典算法之一。

the Bell Lab 

本文的运行效果:

AC算法以模式树(字典树)Trie、广度优先策略和KMP模式匹配算法为核心内容。

using System;
using System.Collections;
using System.Collections.Generic;

namespace Legalsoft.Truffer.Algorithm
{
    /// <summary>
    /// Aho_Corasick 算法
    /// </summary>
    public static partial class PatternSearch
    {
        private static int MAXS = 512;
        private static int MAXC = 26;

        private static int[] outt = new int[MAXS];

        private static int[] f = new int[MAXS];

        private static int[,] g = new int[MAXS, MAXC];

        private static int buildMatchingMachine(string[] arr, int k)
        {
            for (int i = 0; i < outt.Length; i++)
            {
                outt[i] = 0;
            }

            for (int i = 0; i < MAXS; i++)
            {
                for (int j = 0; j < MAXC; j++)
                {
                    g[i, j] = -1;
                }
            }

            int states = 1;
            for (int i = 0; i < k; ++i)
            {
                string word = arr[i];
                int currentState = 0;

                for (int j = 0; j < word.Length; ++j)
                {
                    int ch = word[j] - 'A';
                    if (g[currentState, ch] == -1)
                    {
                        g[currentState, ch] = states++;
                    }
                    currentState = g[currentState, ch];
                }

                outt[currentState] |= (1 << i);
            }

            for (int ch = 0; ch < MAXC; ++ch)
            {
                if (g[0, ch] == -1)
                {
                    g[0, ch] = 0;
                }
            }

            for (int i = 0; i < MAXC; i++)
            {
                f[i] = 0;
            }

            Queue<int> q = new Queue<int>();
            for (int ch = 0; ch < MAXC; ++ch)
            {
                if (g[0, ch] != 0)
                {
                    f[g[0, ch]] = 0;
                    q.Enqueue(g[0, ch]);
                }
            }

            while (q.Count != 0)
            {
                int state = q.Peek();
                q.Dequeue();

                for (int ch = 0; ch < MAXC; ++ch)
                {
                    if (g[state, ch] != -1)
                    {
                        int failure = f[state];
                        while (g[failure, ch] == -1)
                        {
                            failure = f[failure];
                        }

                        failure = g[failure, ch];
                        f[g[state, ch]] = failure;

                        outt[g[state, ch]] |= outt[failure];

                        q.Enqueue(g[state, ch]);
                    }
                }
            }
            return states;
        }

        private static int findNextState(int currentState, char nextInput)
        {
            int answer = currentState;
            int ch = nextInput - 'A';

            while (g[answer, ch] == -1)
            {
                answer = f[answer];
            }
            return g[answer, ch];
        }

        public static List<int> Aho_Corasick_Search(string text, string pattern, int k = 1)
        {
            List<int> matchs = new List<int>();

            string[] arr = new string[1] { pattern };
            buildMatchingMachine(arr, k);

            int currentState = 0;

            for (int i = 0; i < text.Length; ++i)
            {
                currentState = findNextState(currentState, text[i]);

                if (outt[currentState] == 0)
                {
                    continue;
                }

                for (int j = 0; j < k; ++j)
                {
                    if ((outt[currentState] & (1 << j)) > 0)
                    {
                        matchs.Add((i - arr[j].Length + 1));
                    }
                }
            }

            return matchs;
        }
    }
}

POWER BY TRUFFER.CN

using System;
using System.Collections;
using System.Collections.Generic;

namespace Legalsoft.Truffer.Algorithm
{
    /// <summary>
    /// Aho_Corasick 算法
    /// </summary>
    public static partial class PatternSearch
    {
        private static int MAXS = 512;
        private static int MAXC = 26;

        private static int[] outt = new int[MAXS];

        private static int[] f = new int[MAXS];

        private static int[,] g = new int[MAXS, MAXC];

        private static int buildMatchingMachine(string[] arr, int k)
        {
            for (int i = 0; i < outt.Length; i++)
            {
                outt[i] = 0;
            }

            for (int i = 0; i < MAXS; i++)
            {
                for (int j = 0; j < MAXC; j++)
                {
                    g[i, j] = -1;
                }
            }

            int states = 1;
            for (int i = 0; i < k; ++i)
            {
                string word = arr[i];
                int currentState = 0;

                for (int j = 0; j < word.Length; ++j)
                {
                    int ch = word[j] - 'A';
                    if (g[currentState, ch] == -1)
                    {
                        g[currentState, ch] = states++;
                    }
                    currentState = g[currentState, ch];
                }

                outt[currentState] |= (1 << i);
            }

            for (int ch = 0; ch < MAXC; ++ch)
            {
                if (g[0, ch] == -1)
                {
                    g[0, ch] = 0;
                }
            }

            for (int i = 0; i < MAXC; i++)
            {
                f[i] = 0;
            }

            Queue<int> q = new Queue<int>();
            for (int ch = 0; ch < MAXC; ++ch)
            {
                if (g[0, ch] != 0)
                {
                    f[g[0, ch]] = 0;
                    q.Enqueue(g[0, ch]);
                }
            }

            while (q.Count != 0)
            {
                int state = q.Peek();
                q.Dequeue();

                for (int ch = 0; ch < MAXC; ++ch)
                {
                    if (g[state, ch] != -1)
                    {
                        int failure = f[state];
                        while (g[failure, ch] == -1)
                        {
                            failure = f[failure];
                        }

                        failure = g[failure, ch];
                        f[g[state, ch]] = failure;

                        outt[g[state, ch]] |= outt[failure];

                        q.Enqueue(g[state, ch]);
                    }
                }
            }
            return states;
        }

        private static int findNextState(int currentState, char nextInput)
        {
            int answer = currentState;
            int ch = nextInput - 'A';

            while (g[answer, ch] == -1)
            {
                answer = f[answer];
            }
            return g[answer, ch];
        }

        public static List<int> Aho_Corasick_Search(string text, string pattern, int k = 1)
        {
            List<int> matchs = new List<int>();

            string[] arr = new string[1] { pattern };
            buildMatchingMachine(arr, k);

            int currentState = 0;

            for (int i = 0; i < text.Length; ++i)
            {
                currentState = findNextState(currentState, text[i]);

                if (outt[currentState] == 0)
                {
                    continue;
                }

                for (int j = 0; j < k; ++j)
                {
                    if ((outt[currentState] & (1 << j)) > 0)
                    {
                        matchs.Add((i - arr[j].Length + 1));
                    }
                }
            }

            return matchs;
        }
    }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1387230.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Android 13.0仿ios的hotseat效果修改hotseat样式

1.概述 在13.0系统产品rom定制化开发中,在项目需求的需要,系统原生Launcher的布局样式很一般,所以需要重新设计ui对布局样式做调整,产品在看到 ios的hotseat效果觉得特别美观,所以要仿ios一样不需要横屏铺满的效果 居中显示就行了,所以就要看hotseat的具体布局显示了 效…

Docker部署Traefik结合内网穿透远程访问Dashboard界面

文章目录 前言1. Docker 部署 Trfɪk2. 本地访问traefik测试3. Linux 安装cpolar4. 配置Traefik公网访问地址5. 公网远程访问Traefik6. 固定Traefik公网地址 前言 Trfɪk 是一个云原生的新型的 HTTP 反向代理、负载均衡软件&#xff0c;能轻易的部署微服务。它支持多种后端 (D…

『 C++ 』AVL树详解 ( 万字 )

&#x1f988;STL容器类型 在STL的容器中,分为几种容器: 序列式容器&#xff08;Sequence Containers&#xff09;: 这些容器以线性顺序存储元素&#xff0c;保留了元素的插入顺序。 支持随机访问&#xff0c;因此可以使用索引或迭代器快速访问任何位置的元素。 主要的序列式…

tensorflow报错: DNN library is no found

错误描述 如上图在执行程序的时候&#xff0c;会出现 DNN library is no found 的报错 解决办法 这个错误基本上说明你安装的 cudnn有问题&#xff0c;或者没有安装这个工具。 首先检测一下你是否安装了 cudnn 进入CUDA_HOME下&#xff0c;也就是进入你的cuda的驱动的安装目…

【Leetcode 78】子集 —— 回溯法

78. 子集 给你一个整数数组nums&#xff0c;数组中的元素 互不相同 。返回该数组所有可能的子集&#xff08;幂集&#xff09;。 解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。 示例 1&#xff1a; 输入&#xff1a;nums [1,2,3] 输出&#xff1a;[[],[1],[2],[…

记ubuntu2004通过NetworkManager修改网络的优先级

这里写自定义目录标题 前言步骤 前言 起因在于万恶的校园网&#xff0c;突然台式有线死活没法认证&#xff08;感觉是IP冲突了&#xff1f;另外一台电脑同样的系统就没有问题&#xff0c;连路由器WIFI也是可以的&#xff0c;路由器设置的是桥接模式&#xff0c;有没有大佬提供…

欧盟产品安全新规来袭,亚马逊发出紧急提醒(GPSR)要求

欧盟产品安全新规来袭&#xff0c;亚马逊发出紧急提醒&#xff08;GPSR&#xff09;要求 一、发布新规 这世界上唯一不变的事&#xff0c;或许就是变化本身。 在跨境电商领域&#xff0c;这个道理再次得到验证。近日&#xff0c;不少卖家都收到了一封来自亚马逊的通知。通知中…

德语B2 SampleAcademy

德语B2 SampleAcademy 一, Zweigliedrige Konnektion1, entweder... oder2, nicht nur... sondern auch3,sowohl... als auch4,einerseits... andererseits5, zwar...aber6, weder...noch7,je...desto/umso 一, Zweigliedrige Konnektion discontinuous conjunctions 1,…

图解python | 基础数据类型

1.Python变量类型 Python基本数据类型一般分为6种&#xff1a;数值&#xff08;Numbers&#xff09;、字符串&#xff08;String&#xff09;、列表&#xff08;List&#xff09;、元组&#xff08;Tuple&#xff09;、字典&#xff08;Dictionary&#xff09;、集合&#xff…

记一个有关 Vuetify 组件遇到的一些问题

Vuetify 官网地址 所有Vuetify 组件 — Vuetify 1、Combobox使用对象数组 Combobox 组合框 — Vuetify items数据使用对象数组时&#xff0c;默认选中的是整个对象&#xff0c;要对数据进行处理 <v-comboboxv-model"defaultInfo.variableKey":rules"rules…

基于Springboot的善筹网(众筹网-有报告)。Javaee项目,springboot项目。

演示视频&#xff1a; 基于Springboot的善筹网(众筹网-有报告)。Javaee项目&#xff0c;springboot项目。 项目介绍&#xff1a; 采用M&#xff08;model&#xff09;V&#xff08;view&#xff09;C&#xff08;controller&#xff09;三层体系结构&#xff0c;通过Spring S…

华为云优惠券介绍、种类、领取入口及使用教程

华为云作为国内领先的云服务提供商&#xff0c;为了吸引用户&#xff0c;经常推出各种优惠活动&#xff0c;其中就包括华为云优惠券。通过领取和使用优惠券&#xff0c;可以降低用户上云成本&#xff0c;提升用户上云的使用体验。本文将详细介绍华为云的优惠券&#xff0c;包括…

Pandas.DataFrame.loc[ ] 筛选数据-标签法 详解 含代码 含测试数据集 随Pandas版本持续更新

关于Pandas版本&#xff1a; 本文基于 pandas2.1.2 编写。 关于本文内容更新&#xff1a; 随着pandas的stable版本更迭&#xff0c;本文持续更新&#xff0c;不断完善补充。 Pandas稳定版更新及变动内容整合专题&#xff1a; Pandas稳定版更新及变动迭持续更新。 Pandas API参…

京东年度数据报告-2023全年度笔记本十大热门品牌销量(销额)榜单

2023年度&#xff0c;在电脑办公市场整体销售下滑的环境下&#xff0c;笔记本市场的整体销售也不景气。 根据鲸参谋平台的数据显示&#xff0c;京东平台上笔记本的年度销量为650万&#xff0c;同比下滑约16%&#xff1b;销售额约为330亿&#xff0c;同比下滑约19%。同时&#…

【网络取证篇】Windows终端无法使用ping命令解决方法

【网络取证篇】Windows终端无法使用ping命令解决方法 以Ping命令为例&#xff0c;最近遇到ping命令无法使用的情况&#xff0c;很多情况都是操作系统"环境变量"被改变或没有正确配置导致—【蘇小沐】 目录 1、实验环境&#xff08;一&#xff09;无法ping命令 &a…

MS-DETR: Efficient DETR Training with Mixed Supervision论文学习笔记

论文地址&#xff1a;https://arxiv.org/pdf/2401.03989.pdf 代码地址&#xff08;中稿后开源&#xff09;&#xff1a;GitHub - Atten4Vis/MS-DETR: The official implementation for "MS-DETR: Efficient DETR Training with Mixed Supervision" 摘要 DETR 通过迭代…

LeetCode 144. 94. 145. 二叉树的前序,中序,后续遍历(详解) ੭ ᐕ)੭*⁾⁾

经过前面的二叉树的学习&#xff0c;现在让我们实操来练练手~如果对二叉树还不熟悉的小伙伴可以看看我的这篇博客~数据结构——二叉树&#xff08;先序、中序、后序及层次四种遍历&#xff08;C语言版&#xff09;&#xff09;超详细~ (✧∇✧) Q_Q-CSDN博客 144.二叉树的前序遍…

java+vue基于Spring Boot的渔船出海及海货统计系统

该渔船出海及海货统计系统采用B/S架构、前后端分离进行设计&#xff0c;并采用java语言以及springboot框架进行开发。该系统主要设计并完成了管理过程中的用户注册登录、个人信息修改、用户信息、渔船信息、渔船航班、海货价格、渔船海货、非法举报、渔船黑名单等功能。该系统操…

vulnhub靶场之DC-9

一.环境搭建 1.靶场描述 DC-9 is another purposely built vulnerable lab with the intent of gaining experience in the world of penetration testing. The ultimate goal of this challenge is to get root and to read the one and only flag. Linux skills and famili…

NLP论文阅读记录 - 2021 | WOS 利用 ParsBERT 和预训练 mT5 进行波斯语抽象文本摘要

文章目录 前言0、论文摘要一、Introduction1.1目标问题1.2相关的尝试1.3本文贡献 二.前提三.本文方法A. 序列到序列 ParsBERTB、mT5 四 实验效果4.1数据集4.2 对比模型4.3实施细节4.4评估指标4.5 实验结果4.6 细粒度分析 五 总结思考 前言 Leveraging ParsBERT and Pretrained …