Brute-Force算法
假设 字符串s 和 字符串t,字符串t 的定位就是要在 字符串s 中找到一个与 字符串t 相等的字符串。
就像这样
string s = "asdfffgg"; Console.WriteLine(s.IndexOf("fff"));
返回的结果 是 3
下面用Brute-Force算法实现

using System; namespace ConsoleApplication10 { class Program { static void Main(string[] args) { Console.WriteLine(index("cbbcbcbb", "cbc")); Console.WriteLine(index("cbbcbcbb", "bcb")); //string s = "asdfffgg"; //Console.WriteLine(s.IndexOf("fff")); Console.ReadLine(); } static int index(string s ,string t) { int i = 0, j = 0, k; while (i<s.Length&&j<t.Length) { if (s[i]==t[j]) {//如果相等继续匹配 i++; j++; } else {//不相等时回溯 i = i - j + 1; j = 0; } } if (j>=t.Length) {//匹配成功 k = i - t.Length; } else { k=-1; } return k; } } }

浙公网安备 33010602011771号