前段时间去面试,有几道笔试题,分享一下下!!
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
namespace KMP
{
class KMPClass
{
static void Main(string[] args)
{
KMPMethod();
}
//KMP算法的方法
public static void KMPMethod()
{
Console.WriteLine("请输入目标字符串:");
string s = Console.ReadLine();
Console.WriteLine("请输入模式字符串:");
string t = Console.ReadLine();
while (true)
{
if (t.Length <= s.Length && t.Length!=0 && s.Length!=0)
{
int size=t.Length+1;
int[]p=new int[size];//创建NEXT数组
GetModeNext(t,p);//调用获取Next数组的方法
int indext= Matching(s,t,p);//调用匹配的方法
if (indext == -1)
{
Console.WriteLine("****** 匹配失败!******");
Console.ReadLine();
}
else
{
Console.WriteLine("****** 匹配成功:匹配的位置为:" + indext.ToString() + " ******");
Console.ReadLine();
}
break;
}
Console.WriteLine("*******************************************************************************");
Console.WriteLine("对不起,您输入的字符串长度有误,目标字符串的长度必须大于或等于模式字符串的长度!");
Console.WriteLine("请重新输入目标字符串:");
s = Console.ReadLine();
Console.WriteLine("请重新输入模式字符串:");
t = Console.ReadLine();
}
}
//获取模式字符串的Next数组
public static void GetModeNext(string t,int[] p)
{
p[1] = 0;//首先确定第一个Next数组的元素。
int i = 1;
int j = 0;
while (i < t.Length)
{
if (t[i] == t[j])
{
i++;
j++;
p[i] = j;
}
else if (t[i] != t[j])
{
i++;
p[i] = 0;
j = 0;
}
}
}
//匹配的方法,返回值是在目标字符串中匹配成功的位置
public static int Matching(string s, string t, int[] p)
{
int i=0;
int j=0;
int indext=-1;
while (j < t.Length && i < s.Length)
{
if (s[i] == t[j] || j == 0)
{
i++;
j++;
}
else
{
j = p[j];
}
}
if (j == t.Length )//表示匹配成功
{
indext = i - t.Length + 1;//获取匹配成功的位置
return indext;
}
return indext;
}
}
}