Cambios mínimos de substring necesarios para convertir una string binaria en otra

Dadas dos strings binarias S1 y S2 de tamaño N y M respectivamente, la tarea es encontrar el número mínimo de inversión de substrings de caracteres iguales requeridas para convertir la string S1 a S2 . Si no es posible convertir la string S1 a S2 , imprima “-1” .

Ejemplos:

Entrada: S1 = “100001”, S2 = “110111”
Salida: 2
Explicación:
Inicialmente string S1 = “100001”.
Inversión 1: invierta la substring S1[1, 1], luego la string S1 se convierte en «110001».
Inversión 2: invierta la substring S1[3, 4], luego la string S1 se convierte en «110111».
Después de las inversiones anteriores, la string S1 y S2 son iguales.
Por lo tanto, la cuenta de reversiones es 2.

Entrada: S1 = 101, S2 = 10
Salida: -1

Enfoque: siga los pasos a continuación para resolver este problema:

  • Inicialice una variable, digamos answer , para almacenar el conteo resultante de reversión requerida.
  • Si la longitud de las strings dadas S1 y S2 no es la misma, imprima «-1» .
  • Iterar sobre el rango [0, N – 1] y realizar los siguientes pasos:
    • Si S1[i] y S2[i] no son iguales, itere hasta que S1[i] y S2[i] sean iguales. Incremente la respuesta en 1 ya que la substring actual debe invertirse.
    • De lo contrario, continúe con la siguiente iteración.
  • Después de completar los pasos anteriores, imprima el valor de la respuesta como el volteo resultante de las substrings requeridas.

A continuación se muestra la implementación del enfoque anterior:

C++

// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to count the minimum number
// of reversals required to make the
// given binary strings s1 and s2 same
int canMakeSame(string s1, string s2)
{
    // Stores the minimum count of
    // reversal of substrings required
    int ans = 0;
 
    // If the length of the strings
    // are not the same then return -1
    if (s1.size() != s2.size()) {
        return -1;
    }
 
    int N = s1.length();
 
    // Iterate over each character
    for (int i = 0; i < N; i++) {
 
        // If s1[i] is not
        // equal to s2[i]
        if (s1[i] != s2[i]) {
 
            // Iterate until s1[i] != s2[i]
            while (i < s1.length()
                   && s1[i] != s2[i]) {
                i++;
            }
 
            // Increment answer by 1
            ans++;
        }
    }
 
    // Return the resultant count of
    // reversal of substring required
    return ans;
}
 
// Driver Code
int main()
{
    string S1 = "100001";
    string S2 = "110111";
 
    // Function Call
    cout << canMakeSame(S1, S2);
 
    return 0;
}

Java

// Java program for the above approach
import java.io.*;
class GFG
{
 
  // Function to count the minimum number
  // of reversals required to make the
  // given binary strings s1 and s2 same
  static int canMakeSame(String s1, String s2)
  {
 
    // Stores the minimum count of
    // reversal of substrings required
    int ans = 0;
 
    // If the length of the strings
    // are not the same then return -1
    if (s1.length() != s2.length()) {
      return -1;
    }
 
    int N = s1.length();
 
    // Iterate over each character
    for (int i = 0; i < N; i++)
    {
 
      // If s1[i] is not
      // equal to s2[i]
      if (s1.charAt(i) != s2.charAt(i))
      {
 
        // Iterate until s1[i] != s2[i]
        while (i < s1.length()
               && s1.charAt(i) != s2.charAt(i))
        {
          i++;
        }
 
        // Increment answer by 1
        ans++;
      }
    }
 
    // Return the resultant count of
    // reversal of substring required
    return ans;
  }
 
  // Driver Code
  public static void main(String[] args)
  {
    String S1 = "100001";
    String S2 = "110111";
 
    // Function Call
    System.out.println(canMakeSame(S1, S2));
  }
}
 
// This code is contributed by Dharanendra L V

Python3

# Python3 program for the above approach
 
# Function to count the minimum number
# of reversals required to make the
# given binary strings s1 and s2 same
def canMakeSame(s1, s2) :
     
    # Stores the minimum count of
    # reversal of substrings required
    ans = -1
 
    # If the length of the strings
    # are not the same then return -1
    if (len(s1) != len(s2)) :
        return -1
    N = len(s1)
 
    # Iterate over each character
    for i in range(0, N):
 
        # If s1[i] is not
        # equal to s2[i]
        if (s1[i] != s2[i]) :
 
            # Iterate until s1[i] != s2[i]
            while (i < len(s1)
                and s1[i] != s2[i]) :
                i += 1
             
            # Increment answer by 1
            ans += 1
     
    # Return the resultant count of
    # reversal of subrequired
    return ans
 
# Driver Code
 
S1 = "100001"
S2 = "110111"
 
# Function Call
print(canMakeSame(S1, S2))
 
# This code is contributed by code_hunt.

C#

// C# program for the above approach
using System;
 
class GFG{
 
  // Function to count the minimum number
  // of reversals required to make the
  // given binary strings s1 and s2 same
  static int canMakeSame(string s1, string s2)
  {
 
    // Stores the minimum count of
    // reversal of substrings required
    int ans = 0;
 
    // If the length of the strings
    // are not the same then return -1
    if (s1.Length != s2.Length) {
      return -1;
    }
 
    int N = s1.Length;
 
    // Iterate over each character
    for (int i = 0; i < N; i++)
    {
 
      // If s1[i] is not
      // equal to s2[i]
      if (s1[i] != s2[i])
      {
 
        // Iterate until s1[i] != s2[i]
        while (i < s1.Length
               && s1[i] != s2[i])
        {
          i++;
        }
 
        // Increment answer by 1
        ans++;
      }
    }
 
    // Return the resultant count of
    // reversal of substring required
    return ans;
  }
 
// Driver Code
public static void Main(string[] args)
{
    string S1 = "100001";
    string S2 = "110111";
 
    // Function Call
    Console.Write(canMakeSame(S1, S2));
}
}
 
// This code is contributed by susmitakundugoaldanga.

Javascript

<script>
 
// JavaScript program for the above approach
 
// Function to count the minimum number
// of reversals required to make the
// given binary strings s1 and s2 same
function canMakeSame(s1, s2)
{
    // Stores the minimum count of
    // reversal of substrings required
    var ans = 0;
 
    // If the length of the strings
    // are not the same then return -1
    if (s1.length != s2.length) {
        return -1;
    }
 
    var N = s1.length;
 
    // Iterate over each character
    for (var i = 0; i < N; i++) {
 
        // If s1[i] is not
        // equal to s2[i]
        if (s1[i] != s2[i]) {
 
            // Iterate until s1[i] != s2[i]
            while (i < s1.length
                   && s1[i] != s2[i]) {
                i++;
            }
 
            // Increment answer by 1
            ans++;
        }
    }
 
    // Return the resultant count of
    // reversal of substring required
    return ans;
}
 
// Driver Code
var S1 = "100001";
var S2 = "110111";
 
// Function Call
document.write( canMakeSame(S1, S2));
 
</script>
Producción: 

2

 

Complejidad temporal: O(N)
Espacio auxiliar: O(1)

Publicación traducida automáticamente

Artículo escrito por sagnikmukherjee2 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *