Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
СиАОД Архангельский М.В. БСТ-2154.docx
Скачиваний:
16
Добавлен:
01.05.2023
Размер:
162.71 Кб
Скачать

Приложение в Листинг программы задания №3

using System;

using System.Diagnostics;

using System.Windows.Forms;

namespace lab3

{

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

}

private int SearchSubstring(string text, string substring)

{

int textLength = text.Length;

int substringLength = substring.Length;

if (substringLength > textLength)

{

return -1;

}

int[] prefixTable = BuildPrefixTable(substring);

int j = 0;

for (int i = 0; i < textLength; i++)

{

while (j > 0 && text[i] != substring[j])

{

j = prefixTable[j - 1];

}

if (text[i] == substring[j])

{

j++;

}

if (j == substringLength)

{

return i - substringLength + 1;

}

}

return -1;

}

private int[] BuildPrefixTable(string pattern)

{

int patternLength = pattern.Length;

int[] prefixTable = new int[patternLength];

int j = 0;

for (int i = 1; i < patternLength; i++)

{

while (j > 0 && pattern[i] != pattern[j])

{

j = prefixTable[j - 1];

}

if (pattern[i] == pattern[j])

{

j++;

}

prefixTable[i] = j;

}

return prefixTable;

}

private void button1_Click(object sender, EventArgs e)

{

string text = textBox1.Text;

string substring = textBox2.Text;

bool caseSensitive = checkBox1.Checked;

if (string.IsNullOrWhiteSpace(text) || string.IsNullOrWhiteSpace(substring))

{

MessageBox.Show("Пожалуйста, введите исходную строку и подстроку.");

return;

}

if (!caseSensitive)

{

text = text.ToLower();

substring = substring.ToLower();

}

Stopwatch stopwatch = new Stopwatch();

stopwatch.Start();

int index = SearchSubstring(text, substring);

stopwatch.Stop();

if (index != -1)

{

label1.Text = $"Подстрока найдена на позиции: {index}";

}

else

{

label1.Text = "Подстрока не найдена";

}

label2.Text = $"Время работы алгоритма: {stopwatch.ElapsedMilliseconds} мс";

}

}

}