KMP算法(java、C#)

文章目录

kmp中的nextVal(代码用next数组表示)

cs 复制代码
namespace Testmain
{
    public class GetNext
    {
        int[] next;
        public int[] getNextArray(char[] ch)
        {
            next = new int[ch.Length];
            int i = 0, j = -1;
            next[0] = -1;
            while (i < ch.Length - 1)
            {
                if (j == -1 || ch[i] == ch[j])
                {
                    i++;
                    j++;
                    if (ch[i] != ch[j])
                    {
                        next[i] = j;
                    }
                    else
                    {
                        next[i] = next[j];
                    }
                }
                else
                {
                    j = next[j];
                }
            }
            return next;
        }
    }
}

获取匹配成功的主串下标

cs 复制代码
namespace Testmain
{
    public class Index_KMP
    {
        public int getIndex(char[] S, char[] T)
        {
            int i = 0;//main string
            int j = 0;//model string
            int[] next = new int[255];
            GetNext getNext = new GetNext();
            next = getNext.getNextArray(T);
            while (i <= S.Length - 1 && j <= T.Length - 1)
            {
                if (j == -1 || S[i] == T[j])
                {
                    ++i;
                    ++j;
                }
                else
                {
                    j = next[j];
                }
            }
            if (j > T.Length - 1)
            {
                return i - j;
            }
            else
            {
                return 0;
            }
        }
    }
}

程序入口(示例)

cs 复制代码
using System;
namespace Testmain
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                char[] S = { 'w', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'a', 'a', 'b', 'a', 'm' };
                char[] chars = { 'a', 'b', 'a', 'b', 'a', 'a', 'a', 'b', 'a' };
                Index_KMP index_KMP = new Index_KMP();
                var A = index_KMP.getIndex(S, chars);
                Console.WriteLine(A);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

        }

    }
}
相关推荐
努力努力再努力wz13 分钟前
【c++进阶系列】:万字详解多态
java·linux·运维·开发语言·c++
秦亿凡16 分钟前
多线程下为什么用ConcurrentHashMap而不是HashMap
java·开发语言
知其然亦知其所以然27 分钟前
SpringAI + Groq 实战:3 分钟教你搭建超快聊天机器人!
java·后端·openai
阿波罗尼亚41 分钟前
ExcelUtils实现 设置内容 插入行 复制行列格式
java·开发语言
Monkey-旭1 小时前
Android 定位技术全解析:从基础实现到精准优化
android·java·kotlin·地图·定位
带刺的坐椅1 小时前
Solon StateMachine 实现状态机使用示例详解
java·solon·状态机
Yyyy4821 小时前
MyCAT高可用
java·运维
NuyoahC1 小时前
笔试——Day46
c++·算法·笔试
我不是程序猿儿1 小时前
【C#】观察者模式 + UI 线程调度、委托讲解
观察者模式·ui·c#
专注VB编程开发20年1 小时前
c# .net支持 NativeAOT 或 Trimming 的库是什么原理
前端·javascript·c#·.net