Dada una string binaria S, la tarea es encontrar el número mínimo de operaciones de invertir como máximo dos caracteres no adyacentes de la string binaria necesarios para eliminar todos los 0.
Ejemplos:
Entrada: S = “110010”
Salida: 2
Explicación:
Paso 1: Voltear los índices 2 y 5. La string se modifica a “111011”
Paso 2: Voltear solo el índice 3. La string se modifica a “111111”.
Por lo tanto, las operaciones mínimas requeridas son 2.Entrada: S= “110”
Salida: 1
Enfoque ingenuo: el enfoque más simple es atravesar la string dada . Para todos los caracteres de la string encontrados como ‘0’, recorra su derecha para encontrar el siguiente ‘ 0 ‘ que no sea adyacente al carácter actual. Invierta ambos caracteres e incremente la respuesta en 1. Si no hay un ‘0’ a la derecha, invierta el carácter actual e incremente la respuesta en 1.
Complejidad de Tiempo: O(N 2 )
Espacio Auxiliar: O(1)
Enfoque eficiente: la idea es almacenar el índice de los caracteres anteriores que deben invertirse. A continuación se muestra la ilustración con la ayuda de los pasos:
- Inicialice dos variables para mantener el índice de 0 s encontrados previamente en la string con -1 .
- Recorra la string y verifique si los dos últimos índices encontrados no son adyacentes, luego incremente el contador en 1. Además, actualice la posición de los dos últimos índices encontrados previamente.
- Finalmente, después de completar el recorrido, incremente el contador en 2 si los dos últimos índices encontrados no son -1 . De lo contrario, incremente el contador en 1 si uno de los últimos índices encontrados no es -1 .
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 find minimum flips // required to remove all 0s from // a given binary string int minOperation(string s) { // Length of given string int n = s.length(); // Stores the indices of // previous 0s int temp1 = -1, temp2 = -1; // Stores the minimum operations int ans = 0; // Traverse string to find minimum // operations to obtain required string for (int i = 0; i < n; i++) { // Current character int curr = s[i]; // If current character is '0' if (curr == '0') { // Update temp1 with current // index, if both temp // variables are empty if (temp1 == -1 && temp2 == -1) { temp1 = i; } // Update temp2 with current // index, if temp1 contains // prev index but temp2 is empty else if (temp1 != -1 && temp2 == -1 && i - temp1 == 1) { temp2 = i; } // If temp1 is not empty else if (temp1 != -1) { // Reset temp1 to -1 temp1 = -1; // Increase ans ans++; } // If temp2 is not empty but // temp1 is empty else if (temp1 == -1 && temp2 != -1 && i - temp2 != 1) { // Reset temp2 to -1 temp2 = -1; // Increase ans ans++; } } } // If both temp variables // are not empty if (temp1 != -1 && temp2 != -1) { ans += 2; } // Otherwise else if (temp1 != -1 || temp2 != -1) { ans += 1; } // Return the answer return ans; } // Driver Code int main() { string s = "110010"; cout << (minOperation(s)); } // This code is contributed by gauravrajput1
Java
// Java program for above approach import java.util.*; class GFG { // Function to find minimum flips // required to remove all 0s from // a given binary string static int minOperation(String s) { // Length of given string int n = s.length(); // Stores the indices of // previous 0s int temp1 = -1, temp2 = -1; // Stores the minimum operations int ans = 0; // Traverse string to find minimum // operations to obtain required string for (int i = 0; i < n; i++) { // Current character int curr = s.charAt(i); // If current character is '0' if (curr == '0') { // Update temp1 with current // index, if both temp // variables are empty if (temp1 == -1 && temp2 == -1) { temp1 = i; } // Update temp2 with current // index, if temp1 contains // prev index but temp2 is empty else if (temp1 != -1 && temp2 == -1 && i - temp1 == 1) { temp2 = i; } // If temp1 is not empty else if (temp1 != -1) { // Reset temp1 to -1 temp1 = -1; // Increase ans ans++; } // If temp2 is not empty but // temp1 is empty else if (temp1 == -1 && temp2 != -1 && i - temp2 != 1) { // Reset temp2 to -1 temp2 = -1; // Increase ans ans++; } } } // If both temp variables are not empty if (temp1 != -1 && temp2 != -1) { ans += 2; } // Otherwise else if (temp1 != -1 || temp2 != -1) { ans += 1; } // Return the answer return ans; } // Driver Code public static void main(String[] args) { String s = "110010"; System.out.println(minOperation(s)); } }
Python3
# Python3 program for above approach # Function to find minimum flips # required to remove all 0s from # a given binary string def minOperation(s): # Length of given string n = len(s) # Stores the indices of # previous 0s temp1 = -1 temp2 = -1 # Stores the minimum operations ans = 0 # Traverse string to find minimum # operations to obtain required string for i in range(n): # Current character curr = s[i] # If current character is '0' if (curr == '0'): # Update temp1 with current # index, if both temp # variables are empty if (temp1 == -1 and temp2 == -1): temp1 = i # Update temp2 with current # index, if temp1 contains # prev index but temp2 is empty elif (temp1 != -1 and temp2 == -1 and i - temp1 == 1): temp2 = i # If temp1 is not empty elif (temp1 != -1): # Reset temp1 to -1 temp1 = -1 # Increase ans ans += 1 # If temp2 is not empty but # temp1 is empty elif (temp1 == -1 and temp2 != -1 and i - temp2 != 1): # Reset temp2 to -1 temp2 = -1 # Increase ans ans += 1 # If both temp variables are not empty if (temp1 != -1 and temp2 != -1): ans += 2 # Otherwise elif (temp1 != -1 or temp2 != -1): ans += 1 # Return the answer return ans # Driver Code if __name__ == '__main__': s = "110010" print(minOperation(s)) # This code is contributed by mohit kumar 29
C#
// C# program for // the above approach using System; class GFG{ // Function to find minimum flips // required to remove all 0s from // a given binary string static int minOperation(String s) { // Length of given string int n = s.Length; // Stores the indices of // previous 0s int temp1 = -1, temp2 = -1; // Stores the minimum operations int ans = 0; // Traverse string to find minimum // operations to obtain required string for (int i = 0; i < n; i++) { // Current character int curr = s[i]; // If current character is '0' if (curr == '0') { // Update temp1 with current // index, if both temp // variables are empty if (temp1 == -1 && temp2 == -1) { temp1 = i; } // Update temp2 with current // index, if temp1 contains // prev index but temp2 is empty else if (temp1 != -1 && temp2 == -1 && i - temp1 == 1) { temp2 = i; } // If temp1 is not empty else if (temp1 != -1) { // Reset temp1 to -1 temp1 = -1; // Increase ans ans++; } // If temp2 is not empty but // temp1 is empty else if (temp1 == -1 && temp2 != -1 && i - temp2 != 1) { // Reset temp2 to -1 temp2 = -1; // Increase ans ans++; } } } // If both temp variables // are not empty if (temp1 != -1 && temp2 != -1) { ans += 2; } // Otherwise else if (temp1 != -1 || temp2 != -1) { ans += 1; } // Return the answer return ans; } // Driver Code public static void Main(String[] args) { String s = "110010"; Console.WriteLine(minOperation(s)); } } // This code is contributed by Rajput-Ji
Javascript
<script> // Javascript program for // the above approach // Function to find minimum flips // required to remove all 0s from // a given binary string function minOperation(s) { // Length of given string var n = s.length; // Stores the indices of // previous 0s var temp1 = -1, temp2 = -1; // Stores the minimum operations var ans = 0; // Traverse string to find minimum // operations to obtain required string for (var i = 0; i < n; i++) { // Current character var curr = s[i]; // If current character is '0' if (curr == '0') { // Update temp1 with current // index, if both temp // variables are empty if (temp1 == -1 && temp2 == -1) { temp1 = i; } // Update temp2 with current // index, if temp1 contains // prev index but temp2 is empty else if (temp1 != -1 && temp2 == -1 && i - temp1 == 1) { temp2 = i; } // If temp1 is not empty else if (temp1 != -1) { // Reset temp1 to -1 temp1 = -1; // Increase ans ans++; } // If temp2 is not empty but // temp1 is empty else if (temp1 == -1 && temp2 != -1 && i - temp2 != 1) { // Reset temp2 to -1 temp2 = -1; // Increase ans ans++; } } } // If both temp variables // are not empty if (temp1 != -1 && temp2 != -1) { ans += 2; } // Otherwise else if (temp1 != -1 || temp2 != -1) { ans += 1; } // Return the answer return ans; } // Driver Code var s = "110010"; document.write(minOperation(s)); </script>
2
Complejidad temporal: O(N)
Espacio auxiliar: O(1)