Tark_Wight

AhoCorasick

Jul 1st, 2023
209
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.27 KB | Source Code | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. public class AhoCorasick
  5. {
  6.     public static List<int> SearchOccurrences(string text)
  7.     {
  8.         int n = text.Length;
  9.         List<int> pi = new List<int>(n);
  10.         for (int i = 0; i < n; i++)
  11.         {
  12.             pi.Add(0);
  13.         }
  14.  
  15.         for (int i = 1; i < n; i++)
  16.         {
  17.             int j = pi[i - 1];
  18.             while (j > 0 && text[i] != text[j])
  19.             {
  20.                 j = pi[j - 1];
  21.             }
  22.             if (text[i] == text[j])
  23.             {
  24.                 j++;
  25.             }
  26.             pi[i] = j;
  27.         }
  28.  
  29.         return pi;
  30.     }
  31.  
  32.     public static void Main()
  33.     {
  34.         string text = Console.ReadLine();
  35.         int numPatterns = int.Parse(Console.ReadLine());
  36.  
  37.         for (int i = 0; i < numPatterns; i++)
  38.         {
  39.             string pattern = Console.ReadLine();
  40.             string temp = pattern + "#" + text;
  41.             List<int> pi = SearchOccurrences(temp);
  42.             for (int j = pattern.Length; j < pi.Count; j++)
  43.             {
  44.                 if (pi[j] == pattern.Length)
  45.                 {
  46.                     Console.Write(j - 2 * pattern.Length + 1 + " ");
  47.                 }
  48.             }
  49.         }
  50.  
  51.         Console.WriteLine();
  52.     }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment