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>主串</param> /// <param>子串</param> /// <param>主串下标</param> /// <param>子串下标</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; } } }