KMP算法C#实现
2013-12-14 16:18
281 查看
next函数 求出模式串 向右滑动位数
将模式串的str的next函数值 存入 数组next
static void GetNextVal(string str, int [] next)
{
int i = 0;
int j = -1;
next[0] = -1;
while (i < str.Length - 1)
{
if (j == -1 || str[i] == str[j])
{
i++;
j++;
next[i] = j;
}
else
{
j = next[j];
}
}
}
KMP算法
static int KMP(string zstr, string mstr)
{
int i, j;
int[] next = new int[mstr.Length];
GetNextVal(mstr, next);
i = 0;
j = 0;
while (i < zstr.Length && j < mstr.Length)
{
if (j == -1 || zstr[i] == mstr[j])
{
++i;
++j;
}
else
{
j = next[j];
}
}
if (j == mstr.Length)
return i - mstr.Length;
return -1;
}
static void Main(string[] args)
{
string zstr, mstr;
zstr = Console.ReadLine();
mstr = Console.ReadLine();
int pos1;
pos1 = KMP(zstr, mstr);
if (pos1 == -1) Console.WriteLine("没有匹配的字符串!");
else Console.WriteLine(pos1);
Console.Write("请按任意键继续。。");
Console.ReadKey(true);
}
}
将模式串的str的next函数值 存入 数组next
static void GetNextVal(string str, int [] next)
{
int i = 0;
int j = -1;
next[0] = -1;
while (i < str.Length - 1)
{
if (j == -1 || str[i] == str[j])
{
i++;
j++;
next[i] = j;
}
else
{
j = next[j];
}
}
}
KMP算法
static int KMP(string zstr, string mstr)
{
int i, j;
int[] next = new int[mstr.Length];
GetNextVal(mstr, next);
i = 0;
j = 0;
while (i < zstr.Length && j < mstr.Length)
{
if (j == -1 || zstr[i] == mstr[j])
{
++i;
++j;
}
else
{
j = next[j];
}
}
if (j == mstr.Length)
return i - mstr.Length;
return -1;
}
static void Main(string[] args)
{
string zstr, mstr;
zstr = Console.ReadLine();
mstr = Console.ReadLine();
int pos1;
pos1 = KMP(zstr, mstr);
if (pos1 == -1) Console.WriteLine("没有匹配的字符串!");
else Console.WriteLine(pos1);
Console.Write("请按任意键继续。。");
Console.ReadKey(true);
}
}
相关文章推荐
- KMP算法C#实现
- 终于可以实现后台自动更新了
- MD5的Java Bean实现
- SQL查询语句对象化的实现(C#
- Flash聊天室的实现[1]
- ADO.NET实现XML数据库应用
- 智能指针单例模式的实现
- C#实现将字符串作为表达式运算
- JasperReport实现的网络办公系统报表(二):系统技术说明书
- 利用OSGI声明服务实现Corba服务的改善
- PHP实现对文本数据库的数据显示、加入、修改、删除、查询五大基本操作的方法
- 基于Windows CE5.0的双模终端系统设计与实现
- jsp图片验证码实现及getOutputStream() has already been called for this response异常
- 查找算法集:顺序查找、二分查找、插值查找、动态查找(数组实现、链表实现)
- usb摄像头驱动实现源码(spac5xx)分析
- 一个算法的C实现
- 使用用户控件实现主/从场景
- 使用纯XAML标记实现数据验证错误提示
- HttpSessionBindingListener 实现在线用户统计
- Android是否可以实现静默安装模式