我自己写的,有错误,请帮忙修改一下
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();
}
}}
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();
}
}}
解决方案 »
- c# txt文档ansi转UTF-8的问题
- 未能加载文件或程序集“CrystalDecisions.Web, Version=10.5.3700.0, Culture=neutral, PublicKey
- 用户登录验证
- 又来送分啦!!哈哈,快来呀!
- UltraGrid导出excel保留小数点位数的问题
- 静态页面提交给静态页面和动态页面有区别吗?
- C#求助!读取ACCESS中数据写到SQL中,每次都是异常,有代码
- 呵呵,大家好!我想请问c#里在一个主窗体上保存一张或多张图片的代码,赶快来拿分把!
- 线程Join about
- C#如何监控文件夹被删除?
- Bug管理系统
- 网络编程中,使用Socket和TcpClient有什么区别?
断点调试怎么搞?
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();
}
}}