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

        }

    }
}
相关推荐
豆豆酱18 分钟前
Informer方法论详解
算法
槐月初叁22 分钟前
多模态推荐系统指标总结
算法
迪小莫学AI38 分钟前
LeetCode 2588: 统计美丽子数组数目
算法·leetcode·职场和发展
昂子的博客1 小时前
热门面试题第十天|Leetcode150. 逆波兰表达式求值 239. 滑动窗口最大值 347.前 K 个高频元素
算法
Forget the Dream1 小时前
设计模式之迭代器模式
java·c++·设计模式·迭代器模式
緣木求魚1 小时前
c#结合IL(中间语言)分析Try-Catch的内部机制及其对性能的影响
c#·il
qq_297908011 小时前
c#财务软件专业版企业会计做账软件财务管理系统软件
sqlserver·开源·c#
咩咩觉主1 小时前
C# &Unity 唐老狮 No.7 模拟面试题
开发语言·unity·c#
大丈夫在世当日食一鲲1 小时前
Java中用到的设计模式
java·开发语言·设计模式
A-Kamen1 小时前
Spring Boot拦截器(Interceptor)与过滤器(Filter)深度解析:区别、实现与实战指南
java·spring boot·后端