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);
            }

        }

    }
}
相关推荐
致Great4 小时前
大模型对齐核心技术:从第一性原理完整推导 PPO 算法!
人工智能·算法·大模型·agent·智能体
_w_z_j_4 小时前
二叉树的右视图(BFS或DFS)
算法·深度优先·宽度优先
w_zero_one4 小时前
Java的Vert.x框架结合Thymeleaf(TH)模板语言
java·开发语言·idea
咸鱼2.04 小时前
【java入门到放弃】网络
java·开发语言·网络
cyyt4 小时前
深度学习周报(12.22~12.28)
人工智能·算法·机器学习
WBluuue4 小时前
Codeforces Global 31 Div1+2(ABCD)
c++·算法
Roye_ack4 小时前
【微服务 Day2】SpringCloud实战开发(微服务拆分步骤 + Nacos注册中心 + OpenFeign + 微服务拆分作业)
java·spring cloud·微服务·nacos·openfeign
wniuniu_4 小时前
blob是啥
java·服务器·网络
.生产的驴4 小时前
DockerCompoe 部署注册中心Nacos 一键部署 单机+Mysql8
java·linux·运维·spring boot·缓存·docker·doc
会员果汁4 小时前
算法-并查集-C
c语言·开发语言·算法