kmp算法

xiaotupansy 2006-12-06 10:17:41
我自己写的,有错误,请帮忙修改一下


using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication22
{

class Program
{
public static int[] GetNext(string a)
{
int[] next = new int[a.Length];
next[0] = 0;
int j = 0;
int i = 1;
while (i < a.Length - 1)
{

if (j == 0 || a[i] == a[j])
{
++i;
++j;
if (a[i] != a[j])
{
next[i] = j+1;
}
else
{
next[i] = next[j];
}

}
else
{
j = next[j];
}

}
return next;
}

static void Main(string[] args)
{
string s = "abaabc";
foreach (int i in Program.GetNext(s))
Console.WriteLine(i.ToString());

Console.ReadLine();
}
}

}
...全文
214 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
liujia_0421 2006-12-08
  • 打赏
  • 举报
回复
呵呵,靠自己搞定,是不是很有成就感?
xiaotupansy 2006-12-07
  • 打赏
  • 举报
回复
zc是主串
ppc是匹配串
xiaotupansy 2006-12-07
  • 打赏
  • 举报
回复
搞定了,大家帮忙测试一下可不可以
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication22
{

class Program
{
public static int[] GetNext(string a)
{
int[] next = new int[a.Length];
next[0] = 0;
int i = 0;
int j = 0;
while (i < next.Length - 1)
{
if (j == 0 || a[i] == a[j - 1])
{
++i;
++j;
if (a[i] != a[j - 1])
next[i] = j;
else
next[i] = next[j - 1];
}
else
j = next[j - 1];
}

return next;
}
public static int KMP(string zc, string ppc)
{
int[] next = Program.GetNext(ppc);
int i = 0; int j = 0;
while (i < zc.Length && j < ppc.Length)
{
if (j == 0 || zc[i] == ppc[j - 1])
{
++i;
++j;
}
else
j = next[j - 1];
}
if (j >= ppc.Length)
return i - ppc.Length + 1;//匹配的话返回startindex
else
return -1;//不匹配的话返回-1
}
static void Main(string[] args)
{
string s = "六章护";
string b = "第一百四十六章护花倾情";
Console.WriteLine(Program.KMP(b, s).ToString());
Console.WriteLine(b.Substring(Program.KMP(b, s), s.Length));
Console.ReadLine();
}
}

}
xiaotupansy 2006-12-07
  • 打赏
  • 举报
回复
求到正确的next函数值
断点调试怎么搞?
湖中仙人 2006-12-07
  • 打赏
  • 举报
回复
实现什么效果啊?
liujia_0421 2006-12-07
  • 打赏
  • 举报
回复
自己断点调试一下...

要学会自己找问题啊..
xiaotupansy 2006-12-06
  • 打赏
  • 举报
回复
不要百度一下撒,那个我也会
zhaochong12 2006-12-06
  • 打赏
  • 举报
回复
http://blog.chinaitlab.com/user1/295958/archives/2005/30347.html

110,549

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧