Алгоритм Кнута-Морриса-Пратта: Подсчитайте количество сравнений, требуемых при поиске образца без повторений - C#
Формулировка задачи:
Нужно сделать такую задачку.
Введите строку текста. Выполните алгоритм Кнута-Mорриса-Пратта. Подсчитайте количе-ство сравнений, требуемых при поиске образца без повторений и с повторениями.
Но я не понимаю данного алгоритма.. Кто может помочь с программой или как-то объяснить алгоритм?
Решение задачи: «Алгоритм Кнута-Морриса-Пратта: Подсчитайте количество сравнений, требуемых при поиске образца без повторений»
textual
Листинг программы
using System;
using System.IO;
namespace justForFun
{
class MainClass
{
public static void Main (string[] args)
{
Console.WriteLine( "Input filepath and press enter" );
string filePath = Console.ReadLine();
Console.WriteLine( "Input searched string" );
string pattern = Console.ReadLine();
string text = "";
try
{
text = File.ReadAllText( filePath );
}
catch( FileNotFoundException exception )
{
Console.WriteLine("File " + filePath + " not found" );
Console.ReadLine();
return;
}
try
{
int position = FindSubstring( text, pattern );
Console.WriteLine(position);
}
catch(ArgumentException exception)
{
Console.WriteLine(exception);
}
Console.ReadLine();
}
private static int FindSubstring (string input, string pattern)
{
int n = input.Length;
int m = pattern.Length;
if (0 == n)
throw new ArgumentException ("String mustn't be empty", "input");
if (0 == m)
throw new ArgumentException ("String mustn't be empty", "pattern");
int[] d = GetPrefixFunction (pattern);
int i, j;
for (i = 0,j = 0; (i < n) && (j < m); i++,j++)
while ((j >= 0) && (pattern[j] != input[i]))
j = d[j];
if (j == m)
return i - j;
else
return -1;
}
private static int[] GetPrefixFunction (string pattern)
{
int length = pattern.Length;
int[] result = new int[length];
int i = 0;
int j = -1;
result[0] = -1;
while (i < length - 1) {
while ((j >= 0) && (pattern[j] != pattern[i]))
j = result[j];
i++;
j++;
if (pattern[i] == pattern[j])
result[i] = result[j];
else
result[i] = j;
}
return result;
}
}
}