110,534
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Collections.Generic;
using System.Text;
namespace kmp
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static int[] next = new int[200];
static int count = 0;
[STAThread]
static void Main(string[] args)
{
//
// TODO: Add code to start application here
//
int pos = 0, reval;
char[] p1 = @"近日,我国两艘海洋调查船前往钓鱼岛附近(海域)活动,却被日本海上保安厅巡逻舰强行驱离。日本方面就此大做文章,(各大媒体)网站都在显著位置报道称“中国海洋调查船入侵日本领海”。(日本政府也放出厥词宣称“尖阁诸岛(钓鱼岛)是日本的固有领土”。) ".ToCharArray();
char[] p2 = @"近日,我国两艘海洋调查船前往钓鱼岛附近活动,却被日本海上保安厅巡逻舰强行驱离。日本方面就此大做文章,网站都在显著位置报道称“中国海洋调查船入侵日本领海”。".ToCharArray();
Console.WriteLine("第一个文字段长度为{0},第二个文字段长度为{1}", p1.Length, p2.Length);
get_goodnext(p2, next);
reval = index_kmp(p1, p2, pos);
Console.WriteLine("====this is good kmp ====");
Console.WriteLine("value={0},count={1}", reval, count);
Console.ReadLine();
}
static int index_kmp(char[] a, char[] b, int pos)
{
int i = pos, j = 0;
int lena = a.Length, lenb = b.Length;
count = 0;
while ((i <= lena - 1) && (j <= lenb - 1))
{
if (j == -1 || a[i] == b[j])
{ ++i; ++j;count++; }
else
{ j = next[j]; }
}
if (j > lenb - 1)
return i - lenb;
else
return 0;
}
static void get_goodnext(char[] a, int[] next)
{
int i = 0, j = -1;
next[0] = -1;
while (i < a.Length - 1)
{
if (j == -1 || a[i] == a[j])
{
++i; ++j;
if (a[i] != a[j])
{
next[i] = j;
}
else
{
next[i] = next[j];
}
}
else
{ j = next[j]; }
}
}
}
}