Número de vueltas para alternar una string binaria | Serie 1

Dada una string binaria, es decir, contiene solo 0 y 1. Necesitamos hacer de esta string una secuencia de caracteres alternativos al voltear algunos de los bits, nuestro objetivo es minimizar la cantidad de bits que se voltearán. 

Ejemplos: 

Input : str = “001”
Output : 1
Minimum number of flips required = 1
We can flip 1st bit from 0 to 1 

Input : str = “0001010111”
Output : 2
Minimum number of flips required = 2
We can flip 2nd bit from 0 to 1 and 9th 
bit from 1 to 0 to make alternate 
string “0101010101”.

Complejidad de tiempo esperada: O(n) donde n es la longitud de la string de entrada.

Podemos resolver este problema considerando todos los resultados posibles. Como se supone que debemos obtener una string alternativa, solo hay 2 posibilidades, una string alternativa que comience con 0 y una string alternativa que comience con 1. Probaremos ambos casos y elegiremos la string que requerirá número mínimo de vueltas como nuestra respuesta final. 

Probar un caso requiere un tiempo O (n) en el que recorreremos todos los caracteres de la string dada, si el carácter actual es el carácter esperado de acuerdo con la alternancia, no haremos nada, de lo contrario, aumentaremos el número de vueltas en 1. Después de probar las strings que comienzan con 0 y comenzando con 1, elegiremos la string con el número mínimo de vueltas. 

La complejidad temporal total de la solución será O(n) 

Implementación:

C++

// C++ program to find minimum number of flip to make binary
// string alternate
#include <bits/stdc++.h>
using namespace std;
 
//  Utility method to flip a character
char flip(char ch) { return (ch == '0') ? '1' : '0'; }
 
//  Utility method to get minimum flips when alternate
//  string starts with expected char
int getFlipWithStartingCharcter(string str, char expected)
{
    int flipCount = 0;
    for (int i = 0; i < str.length(); i++) {
        // if current character is not expected, increase
        // flip count
        if (str[i] != expected)
            flipCount++;
 
        //  flip expected character each time
        expected = flip(expected);
    }
    return flipCount;
}
 
// method return minimum flip to make binary string
// alternate
int minFlipToMakeStringAlternate(string str)
{
    //  return minimum of following two
    //  1) flips when alternate string starts with 0
    //  2) flips when alternate string starts with 1
    return min(getFlipWithStartingCharcter(str, '0'),
               getFlipWithStartingCharcter(str, '1'));
}
 
//  Driver code to test above method
int main()
{
    string str = "0001010111";
    cout << minFlipToMakeStringAlternate(str);
    return 0;
}
 
// This code is contributed by Sania Kumari Gupta
// (kriSania804)

C

// C program to find minimum number of flip to make binary
// string alternate
#include <stdio.h>
#include <string.h>
 
// Find minimum between two numbers.
int min(int num1, int num2)
{
    return (num1 > num2) ? num2 : num1;
}
 
//  Utility method to flip a character
char flip(char ch) { return (ch == '0') ? '1' : '0'; }
 
//  Utility method to get minimum flips when
//  alternate string starts with expected char
int getFlipWithStartingCharcter(char str[], char expected)
{
    int flipCount = 0;
    for (int i = 0; i < strlen(str); i++) {
        //  if current character is not expected,
        // increase flip count
        if (str[i] != expected)
            flipCount++;
 
        //  flip expected character each time
        expected = flip(expected);
    }
    return flipCount;
}
 
// method return minimum flip to make binary
// string alternate
int minFlipToMakeStringAlternate(char str[])
{
    //  return minimum of following two
    //  1) flips when alternate string starts with 0
    //  2) flips when alternate string starts with 1
    return min(getFlipWithStartingCharcter(str, '0'),
               getFlipWithStartingCharcter(str, '1'));
}
 
//  Driver code to test above method
int main()
{
    char str[] = "0001010111";
    printf("%d",minFlipToMakeStringAlternate(str));
    return 0;
}
 
// This code is contributed by Sania Kumari Gupta (kriSania804)

Java

// Java program to find minimum number of
// flip to make binary string alternate
class GFG
{
    //  Utility method to flip a character
    public static char flip(char ch)
    {
        return (ch == '0') ? '1' : '0';
    }
      
    //  Utility method to get minimum flips when
    //  alternate string starts with expected char
    public static int getFlipWithStartingCharcter(String str,
                                    char expected)
    {
        int flipCount = 0;
        for (int i = 0; i < str.length(); i++)
        {
            //  if current character is not expected,
            // increase flip count
            if (str.charAt(i) != expected)
                flipCount++;
      
            //  flip expected character each time
            expected = flip(expected);
        }
        return flipCount;
    }
      
    // method return minimum flip to make binary
    // string alternate
    public static int minFlipToMakeStringAlternate(String str)
    {
        //  return minimum of following two
        //  1) flips when alternate string starts with 0
        //  2) flips when alternate string starts with 1
        return Math.min(getFlipWithStartingCharcter(str, '0'),
                   getFlipWithStartingCharcter(str, '1'));
    }
      
    //  Driver code to test above method
    public static void main(String args[])
    {
        String str = "0001010111";
        System.out.println(minFlipToMakeStringAlternate(str));
    }
}
 
// This code is contributed by Sumit Ghosh

Python 3

# Python 3 program to find minimum number of
# flip to make binary string alternate
 
# Utility method to flip a character
def flip( ch):
    return '1' if (ch == '0') else '0'
 
# Utility method to get minimum flips when
# alternate string starts with expected char
def getFlipWithStartingCharcter(str, expected):
 
    flipCount = 0
    for i in range(len( str)):
         
        # if current character is not expected,
        # increase flip count
        if (str[i] != expected):
            flipCount += 1
 
        # flip expected character each time
        expected = flip(expected)
    return flipCount
 
# method return minimum flip to make binary
# string alternate
def minFlipToMakeStringAlternate(str):
 
    # return minimum of following two
    # 1) flips when alternate string starts with 0
    # 2) flips when alternate string starts with 1
    return min(getFlipWithStartingCharcter(str, '0'),
            getFlipWithStartingCharcter(str, '1'))
 
# Driver code to test above method
if __name__ == "__main__":
     
    str = "0001010111"
    print(minFlipToMakeStringAlternate(str))

C#

// C# program to find minimum number of
// flip to make binary string alternate
using System;
 
class GFG
{
    // Utility method to
    // flip a character
    public static char flip(char ch)
    {
        return (ch == '0') ? '1' : '0';
    }
     
    // Utility method to get minimum flips
    // when alternate string starts with
    // expected char
    public static int getFlipWithStartingCharcter(String str,
                                                char expected)
    {
        int flipCount = 0;
        for (int i = 0; i < str.Length; i++)
        {
            // if current character is not
            // expected, increase flip count
            if (str[i] != expected)
                flipCount++;
     
            // flip expected character each time
            expected = flip(expected);
        }
        return flipCount;
    }
     
    // method return minimum flip to
    // make binary string alternate
    public static int minFlipToMakeStringAlternate(string str)
    {
        // return minimum of following two
        // 1) flips when alternate string starts with 0
        // 2) flips when alternate string starts with 1
        return Math.Min(getFlipWithStartingCharcter(str, '0'),
                getFlipWithStartingCharcter(str, '1'));
    }
     
    // Driver Code
    public static void Main()
    {
        string str = "0001010111";
        Console.Write(minFlipToMakeStringAlternate(str));
    }
}
 
// This code is contributed by nitin mittal.

PHP

<?php
// PHP program to find minimum number of
// flip to make binary string alternate
 
// Utility method to flip a character
function flip( $ch)
{
    return ($ch == '0') ? '1' : '0';
}
 
// Utility method to get minimum flips when
// alternate string starts with expected char
function getFlipWithStartingCharcter($str,
                                $expected)
{
     
    $flipCount = 0;
    for ($i = 0; $i < strlen($str); $i++)
    {
         
        // if current character is not expected,
        // increase flip count
        if ($str[$i] != $expected)
            $flipCount++;
 
        // flip expected character each time
        $expected = flip($expected);
    }
    return $flipCount;
}
 
// method return minimum flip to make binary
// string alternate
function minFlipToMakeStringAlternate( $str)
{
     
    // return minimum of following two
    // 1) flips when alternate string starts with 0
    // 2) flips when alternate string starts with 1
    return min(getFlipWithStartingCharcter($str, '0'),
               getFlipWithStartingCharcter($str, '1'));
}
 
// Driver code to test above method
$str = "0001010111";
echo minFlipToMakeStringAlternate($str);
 
// This code is contributed by anuj_67.
?>

Javascript

<script>
 
// Javascript program to find minimum number of
// flip to make binary string alternate
     
    //  Utility method to flip a character
    function flip(ch)
    {
        return (ch == '0') ? '1' : '0';
    }
     
    //  Utility method to get minimum flips when
    //  alternate string starts with expected char
    function getFlipWithStartingCharcter(str,expected)
    {
        let flipCount = 0;
        for (let i = 0; i < str.length; i++)
        {
            //  if current character is not expected,
            // increase flip count
            if (str.charAt(i) != expected)
                flipCount++;
        
            //  flip expected character each time
            expected = flip(expected);
        }
        return flipCount;
    }
     
    // method return minimum flip to make binary
    // string alternate
    function minFlipToMakeStringAlternate(str)
    {
         //  return minimum of following two
        //  1) flips when alternate string starts with 0
        //  2) flips when alternate string starts with 1
        return Math.min(getFlipWithStartingCharcter(str, '0'),
                   getFlipWithStartingCharcter(str, '1'));
    }
     
    //  Driver code to test above method
    let str = "0001010111";
    document.write(minFlipToMakeStringAlternate(str));
     
    // This code is contributed by avanitrachhadiya2155
     
</script>
Producción

2

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

Número mínimo de reemplazos para hacer que la string binaria se alterné | conjunto 2 

Este artículo es una contribución de Utkarsh Trivedi . Si te gusta GeeksforGeeks y te gustaría contribuir, también puedes escribir un artículo usando write.geeksforgeeks.org o enviar tu artículo por correo a review-team@geeksforgeeks.org. Vea su artículo que aparece en la página principal de GeeksforGeeks y ayude a otros Geeks. 

Publicación traducida automáticamente

Artículo escrito por GeeksforGeeks-1 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 *