Compruebe si una string binaria contiene el mismo consecutivo o no

Dada una string binaria str que consta de los caracteres ‘0’ y ‘1’ . La tarea es encontrar si la string es válida o no. Una string es válida sólo si los caracteres se alternan, es decir, no hay dos caracteres consecutivos iguales.
Ejemplos: 
 

Entrada: str[] = “010101” 
Salida: Válido
Entrada: str[] = “010010” 
Salida: No válido 
 

Enfoque: Comience a recorrer la string carácter por carácter y si hay dos caracteres consecutivos que son iguales, imprima No válido ; de lo contrario, imprima Válido al final.
A continuación se muestra la implementación del enfoque anterior: 
 

C++

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function that returns true is str is valid
bool isValid(string str, int len)
{
 
    // Assuming the string is binary
    // If any two consecutive characters are equal
    // then the string is invalid
    for (int i = 1; i < len; i++) {
        if (str[i] == str[i - 1])
            return false;
    }
 
    // If the string is alternating
    return true;
}
 
// Driver code
int main()
{
    string str = "0110";
    int len = str.length();
 
    if (isValid(str, len))
        cout << "Valid";
    else
        cout << "Invalid";
 
    return 0;
}

Java

// Java implementation of the approach
class gfg
{
     
// Function that returns true is str is valid
static boolean isValid(String str, int len)
{
 
    // Assuming the string is binary
    // If any two consecutive
    // characters are equal
    // then the string is invalid
    for (int i = 1; i < len; i++)
    {
        if (str.charAt(i) == str.charAt(i - 1))
            return false;
    }
 
    // If the string is alternating
    return true;
}
 
// Driver code
public static void main(String[] args)
{
    String str = "0110";
    int len = str.length();
 
    if (isValid(str, len))
        System.out.println("Valid");
    else
        System.out.println("Invalid");
}
}
 
// This code is Contributed by Code_Mech

Python3

# Python3 implementation of the approach
 
# Function that returns true is str is valid
def isValid(string, length):
 
    # Assuming the string is binary
    # If any two consecutive characters
    # are equal then the string is invalid
    for i in range(1, length):
        if string[i] == string[i - 1]:
            return False
 
    # If the string is alternating
    return True
 
# Driver code
if __name__ == "__main__":
 
    string = "0110"
    length = len(string)
 
    if isValid(string, length):
        print("Valid")
    else:
        print("Invalid")
 
# This code is contributed by Rituraj Jain

C#

// C# implementation of the approach
using System;
 
class gfg
{
     
// Function that returns true is str is valid
static bool isValid(string str, int len)
{
 
    // Assuming the string is binary
    // If any two consecutive
    // characters are equal
    // then the string is invalid
    for (int i = 1; i < len; i++)
    {
        if (str[i] == str[i - 1])
            return false;
    }
 
    // If the string is alternating
    return true;
}
 
// Driver code
public static void Main()
{
    string str = "0110";
    int len = str.Length;
 
    if (isValid(str, len))
        Console.Write("Valid");
    else
        Console.Write("Invalid");
}
}
 
// This code is contributed by Ita_c.

PHP

<?php
// PHP implementation of the approach
 
// Function that returns true is str is valid
function isValid($str, $len)
{
 
    // Assuming the string is binary
    // If any two consecutive characters
    // are equal then the string is invalid
    for ($i = 1; $i < $len; $i++)
    {
        if ($str[$i] == $str[$i - 1])
            return false;
    }
 
    // If the string is alternating
    return true;
}
 
// Driver code
$str = "0110";
$len = strlen($str);
 
if (isValid($str, $len))
    echo "Valid";
else
    echo "Invalid";
 
// This code is contributed by Ryuga
?>

Javascript

<script>
// Javascript implementation of the approach
 
// Function that returns true is str is valid
function isValid(str,len)
{
    // Assuming the string is binary
    // If any two consecutive
    // characters are equal
    // then the string is invalid
    for (let i = 1; i < len; i++)
    {
        if (str[i] == str[i - 1])
            return false;
    }
   
    // If the string is alternating
    return true;
}
 
// Driver code
let str = "0110";
let len = str.length;
 
if (isValid(str, len))
    document.write("Valid");
else
    document.write("Invalid");
 
 
// This code is contributed by rag2127
</script>
Producción: 

Invalid

 

Publicación traducida automáticamente

Artículo escrito por Shivam.Pradhan 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 *