using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static int BmSerach(byte[] source, byte[] template)
{
// Prepare BmBc
int[] bmBc = new int[256];
for (int i = 0; i < bmBc.Length; ++i)
bmBc[i] = template.Length;
for (int i = 0; i < template.Length - 1; ++i)
bmBc[template[i]] = template.Length - 1 - i;
// Prepare Suffix
int[] suff = new int[template.Length];
suff[suff.Length - 1] = template.Length;
for (int i = template.Length - 2; i >= 0; --i)
{
int q = i;
while (q >= 0 && template[q] == template[template.Length - 1 - (i - q)])
--q;
suff[i] = i - q;
}
// Prepare BmGs
int[] bmGs = new int[template.Length];
for (int i = 0; i < bmGs.Length - 1; i++)
bmGs[i] = template.Length;
int j = 0;
for (int i = template.Length - 1; i >= 0; --i)
if (suff[i] == i + 1)
for (; j < template.Length - 1 - i; ++j)
if (bmGs[j] == template.Length)
bmGs[j] = template.Length - 1 - i;
for (int i = 0; i <= template.Length - 2; ++i)
bmGs[template.Length - 1 - suff[i]] = template.Length - 1 - i;
bmGs.ToList().ForEach(x => Console.Write(x.ToString() + ' '));
//Trace.WriteLine("");
// Search
j = 0;
while (j < source.Length - template.Length)
{
int i = template.Length - 1;
for (; i >= 0 && template[i] == source[j + i]; i--) ;
if (i < 0)
return j;
else
{
int step = Math.Max(bmBc[source[j + i]], bmGs[i]);
j += step;
Console.WriteLine("STEP:" + j);
}
}
return -1;
}
static void Main(string[] args)
{
loop:
Console.WriteLine("输入文本字符串:");
string a = Console.ReadLine();
Console.WriteLine("输入模板:");
string b = Console.ReadLine();
int i = BmSerach(Encoding.ASCII.GetBytes(a), Encoding.ASCII.GetBytes(b));
Console.WriteLine(i);
goto loop;
}
}
}