编程语言
首页 > 编程语言> > C#BF算法递归实现

C#BF算法递归实现

作者:互联网

BruteForce算法递归实现,少了点慧根

using System;

namespace BruteForce
{
    class Program
    {
        static void Main(string[] args)
        {
            bool run = true;

            while (run)
            {
                Console.WriteLine("BruteForce算法,计算子串在主串中的位置:");
                Console.WriteLine("输入一个主串:");
                string mainString = Console.ReadLine().Trim().ToString();
                Console.WriteLine("输入一个子串:");
                string substring = Console.ReadLine().Trim().ToString();
                Console.WriteLine($"索引位置:{Locating(mainString, substring, 0, 0)}");
            }

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="mainString">主串</param>
        /// <param name="substring">子串</param>
        /// <param name="mIndex">主串下标</param>
        /// <param name="sIndex">子串下标</param>
        /// <returns></returns>
        static string Locating(string mainString, string substring, int mIndex, int sIndex)
        {
            if (mIndex == 0 && sIndex == 0)
            {
                for (int j = sIndex; j < substring.Length; j++)
                {
                    for (int i = mIndex; i < mainString.Length; i++)
                    {
                        if (substring[j] == mainString[i])
                        {
                            if (j == substring.Length - 1 || i == mainString.Length - 1)
                            {
                                return i.ToString();
                            }
                            string res = Locating(mainString, substring, i + 1, j + 1);
                            if (res != null)
                            {
                                return i.ToString();
                            }
                        }
                    }
                }
            }
            else
            {
                if (substring[sIndex] == mainString[mIndex])
                {
                    if (sIndex == substring.Length - 1 || mIndex == mainString.Length - 1)
                    {
                        return sIndex.ToString();
                    }
                    else
                    {
                        string res = Locating(mainString, substring, mIndex + 1, sIndex + 1);
                        if (res != null)
                        {
                            return sIndex.ToString();
                        }
                    }
                }
            }
            return null;
        }
    }
}

 

标签:BF,sIndex,Console,string,递归,C#,mIndex,substring,mainString
来源: https://www.cnblogs.com/yt954437595/p/14608695.html