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

        }

    }
}
相关推荐
Vae_Mars3 分钟前
WPF中的switch选择
开发语言·c#
Bonne journée9 分钟前
‌在Python中,print(f‘‘)是什么?
java·开发语言·python
秋夜Autumn24 分钟前
贪心算法相关知识
算法·贪心算法
2402_8575893630 分钟前
新闻推荐系统:Spring Boot框架详解
java·spring boot·后端
2401_8576226631 分钟前
新闻推荐系统:Spring Boot的可扩展性
java·spring boot·后端
小懒编程日记36 分钟前
【数据结构与算法】B树
java·数据结构·b树·算法
心怀花木43 分钟前
【算法】双指针
c++·算法
闫铁娃1 小时前
二分解题的奇技淫巧都有哪些,你还不会吗?
c语言·数据结构·c++·算法·leetcode
Y_3_71 小时前
【回溯数独】有效的数独(medium)& 解数独(hard)
java·数据结构·windows·算法·dfs·回溯
RangoLei_Lzs1 小时前
C++模版SFIANE应用踩的一个小坑
java·开发语言·ui