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

        }

    }
}
相关推荐
沉鱼.448 分钟前
第十三届题目
c语言·c++·算法
希望永不加班15 分钟前
SpringBoot 静态资源访问(图片/JS/CSS)配置详解
java·javascript·css·spring boot·后端
ZHOU_WUYI16 分钟前
ppo算法简单实现
人工智能·pytorch·算法
oh LAN31 分钟前
RuoYi-Vue-master:Spring Boot 4.x (JDK 17+) (环境搭建)
java·vue.js·spring boot
武藤一雄34 分钟前
C# 异常(Exception)处理避坑指南
windows·microsoft·c#·.net·.netcore·鲁棒性
ch.ju38 分钟前
Java程序设计(第3版)第二章——java的数据类型:小数
java
无限进步_1 小时前
【C++】巧用静态变量与构造函数:一种非常规的求和实现
开发语言·c++·git·算法·leetcode·github·visual studio
Advancer-1 小时前
RedisTemplate 两种序列化实践方案
java·开发语言·redis
小超超爱学习99371 小时前
大数乘法,超级简单模板
开发语言·c++·算法
java1234_小锋1 小时前
Java高频面试题:MyBatis如何实现动态数据源切换?
java·开发语言·mybatis