In: Computer Science
C#
One Away: There are three types of edits that
can be performed on strings: insert a character, remove a
character, or replace a character. Given two strings, write a
function to check if they are one edit (or zero edits) away.
EXAMPLE
pale, pIe -> true
pales. pale -> true
pale. bale -> true
pale. bake -> false
Comment your code to explain it.
C# PROGRAM ===>
using System;
namespace ConsoleApp
{
   class OneEditAway
   {
       static bool isOneEdit(String
s1,String s2)
       {
           // lengths of
strings s1 ,s2
           int m =
s1.Length, n = s2.Length;
           // if
difference is more than one return false
           if (Math.Abs(m -
n) > 1)
{
          
    return false;
           }
          
   
           int count =
0;
           int i = 0, j =
0;
           while (i <
m && j < n)
           {
          
    // If current characters don't match
          
    if (s1[i] != s2[j])
          
    {
          
        if (count == 1)
{
          
            return
false;
          
        }
          
        // If length of one string is
more, then only possible edit is to remove a character
          
        if (m > n)
{
          
            i++;
          
        }
          
        else if (m < n)
{
          
            j++;
          
        }
          
        // If lengths of both strings
is same
          
        else
          
        {
          
            i++;
          
            j++;
          
        }
          
        // Increment count of
edits
          
        count++;
          
    }
          
    // If current characters match
          
    else
          
    {
          
        i++;
          
        j++;
          
    }
           }
           // If last
character is extra in any string
           if (i < m ||
j < n)
{
          
    count++;
           }
          
   
           return count
== 1;
       }
         
       public static void Main()
       {
          
Console.Write("Enter String 1 : ");
           String str1 =
Console.ReadLine();
          
Console.Write("Enter String 2 : ");
           String str2 =
Console.ReadLine();
          
Console.WriteLine();
           if
(isOneEdit(str1, str2))
          
    Console.WriteLine(str1+ " , "+str2+ " -->
"+"true");
           else
          
    Console.WriteLine(str1 + " , " + str2 + " -->
" + "false");
       }
   }
}  
OUTPUT SCREENSHOT ===>


