Advertisement
allia

левенштейн

Mar 3rd, 2021
866
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.73 KB | None | 0 0
  1. using System;
  2. using System.Text;
  3. using System.Collections.Generic;
  4. using System.Text.RegularExpressions;
  5.  
  6. class MainClass
  7. {
  8.   static int Minimum(int a, int b, int c)
  9.  {
  10.    int min = 0;
  11.  
  12.    if (a <= b && a <= c)
  13.     min = a;
  14.    else if (b <= a && b <= c)
  15.     min = b;
  16.    else if (c <= a && c <= b)
  17.     min = c;
  18.    return min;
  19.  }
  20.  
  21.   public static string Replace_s(string str)
  22.   {
  23.     Regex regF = new Regex(@"[^a-z0-9\s]");
  24.             str = regF.Replace(str.ToLower(), string.Empty);
  25.  
  26.             MatchCollection regS = Regex.Matches(str, @"[a-z0-9]{4,}\s?");
  27.  
  28.             str = "";
  29.             foreach (Match match in regS)
  30.             {
  31.               str += match.Value;
  32.             }
  33.  
  34.             return str;
  35.   }
  36.  
  37.   public static int Levenstain(string firstString, string secondString)
  38.   {
  39.    int result;
  40.    int n = firstString.Length + 1;
  41.    int m = secondString.Length + 1;
  42.    int [,] mass = new int[n,m];
  43.  
  44.    for(int i = 0; i < n; i++)
  45.     mass[i,0] = i;
  46.  
  47.   for(int j = 0; j < m; j++)
  48.    mass[0,j] = j;
  49.  
  50.   for(int i = 1; i < n; i++)
  51.      for (int j = 1; j < m; j++)
  52.      {
  53.       int toReplace = 0;
  54.  
  55.       if (secondString[j-1] == firstString[i-1])
  56.        toReplace = 0;
  57.        else toReplace = 1;
  58.  
  59.       mass[i, j] = Minimum(mass[i-1, j] + 1, mass[i,j-1] + 1, mass[i-1, j-1] + toReplace);
  60.      }
  61.    
  62.  
  63.    result = mass[n-1,m-1];
  64.    return result;
  65.   }
  66.   public static void Main(string[] args)
  67.   {
  68.     string firstString;
  69.     string secondString;
  70.  
  71.     firstString = Console.ReadLine();
  72.     secondString = Console.ReadLine();
  73.      firstString = Replace_s(firstString);
  74.      secondString = Replace_s(secondString);
  75.  
  76.     Console.WriteLine(Levenstain(firstString, secondString));
  77. }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement