字符串匹配算法之RK算法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PK
{
    class Program
    {
        static void Main(string[] args)
        {


            Console.WriteLine(RK("abcdef", "abce"));
            Console.WriteLine(RK("abcdef", "ab"));
            Console.WriteLine(RK("abcdef", "bc"));
            Console.WriteLine(RK("abcdef", "cd"));
            Console.WriteLine(RK("abcdef", "de"));
            Console.WriteLine(RK("abcdef", "ef"));
            Console.WriteLine(RK("abcdef", "ef3"));
            Console.ReadKey();
        }



        private static int RK(string resStr, string pStr)
        {
            int result = -1;
            int pStrHash = pStr.GetHashCode();

            int resStrLength = resStr.Length;
            int pStrLength = pStr.Length;


            for (int i = 0; i < resStrLength; i++)
            {
                int stepEnd = i + pStrLength;
                int stepStart = i;
                if (stepEnd > resStrLength) return result;
                string tmpStr = "";
                for (int j = stepStart; j < stepEnd; j++)
                {
                    tmpStr += resStr[j];
                    if (tmpStr.GetHashCode() == pStrHash)
                    {
                        result = stepStart;
                        return result;
                    }
                }
            }
            return result;
        }
    }
}

打印结果:

posted @ 2020-11-18 17:19  围墙外的世界  阅读(335)  评论(0编辑  收藏  举报