Advertisement
Pearlfromsu

knuth morris pratt algorithm c#

May 6th, 2024
754
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.08 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7.  
  8. namespace ClassLibrary1
  9. {
  10.     public class KnutMorrisPratt : ISubstringSearch {
  11.         int[] PrefixFunctionFast(string str)
  12.         {
  13.             int[] result = new int[str.Length];
  14.             result[0] = 0;
  15.             for (int i = 1; i < str.Length; i++)
  16.             {
  17.                 int k = result[i - 1];
  18.                 while (k > 0 && str[k] != str[i])
  19.                 {
  20.                     k = result[k - 1];
  21.                 }
  22.                 if (str[k] == str[i])
  23.                 {
  24.                     k++;
  25.                 }
  26.                 result[i] = k;
  27.             }
  28.             return result;
  29.         }
  30.         int[] PrefixFunction(string str) {
  31.             int n = str.Length;
  32.             int[] p = new int[n];
  33.             for (int i = 0; i < n; i++)
  34.             {
  35.                 for (int k = 0; k < i; k++)
  36.                 {
  37.                     bool fl = true;
  38.                     for (int j = 0; j < k + 1; j++)
  39.                     {
  40.                         if (str[j] != str[i - k + j])
  41.                         {
  42.                             fl = false;
  43.                             break;
  44.                         }
  45.                     }
  46.                     if (fl)
  47.                         p[i] = (byte)(k + 1);
  48.                 }
  49.             }              
  50.             return p;
  51.         }
  52.         public List<int> FindAll(string text, string substring) {
  53.             List<int> res = new List<int>();
  54.             int[] prefix_sub = PrefixFunctionFast(substring);
  55.             int k = 0;
  56.             for(int i = 0; i < text.Length; i++)
  57.             {
  58.                 while (k > 0 && substring[k] != text[i]) { k = prefix_sub[k - 1]; }
  59.                 if (substring[k] == text[i]) k++;
  60.                 if (k == substring.Length)
  61.                 {
  62.                     res.Add(i - k + 1);
  63.                     k = prefix_sub[k - 1];
  64.                 }
  65.             }
  66.             return res;
  67.         }
  68.     }
  69. }
  70.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement