Compruebe si una string binaria tiene dos ocurrencias consecutivas de una en todas partes

Dada la string str que consta solo de los caracteres ‘a’ y ‘b’ , la tarea es verificar si la string es válida o no. En una string válida, cada grupo de b consecutivas debe tener una longitud de 2 y debe aparecer después de 1 o más ocurrencias del carácter ‘a’, es decir , «abba» es una substring válida pero «abbb» y aba no lo son. Imprime 1 si la string es válida, de lo contrario imprime -1 .

Ejemplos: 

Entrada: str = “abbaaabbabba” 
Salida: 1

Entrada: str = “abbaaababb” 
Salida: -1 

Enfoque: busque todas las apariciones de ‘b’ en la string y verifique si es parte de la substring «abb» . Si la condición falla para cualquier substring, imprima -1 ; de lo contrario, imprima 1 .

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 1 if str is valid
bool isValidString(string str, int n)
{
    // Index of first appearance of 'b'
    int index = find(str.begin(),      
                     str.end(), 'b') -
                     str.begin();
 
    // If str starts with 'b'
    if (index == 0)
        return false;
 
    // While 'b' occurs in str
    while (index <= n - 1)
    {
        // If 'b' doesn't appear after an 'a'
        if (str[index - 1] != 'a')
            return false;
 
        // If 'b' is not succeeded by another 'b'
        if (index + 1 < n && str[index + 1] != 'b')
            return false;
 
        // If sub-string is of the type "abbb"
        if (index + 2 < n && str[index + 2] == 'b')
            return false;
 
        // If str ends with a single b
        if (index == n - 1)
            return false;
 
        index = find(str.begin() + index + 2,
                     str.end(), 'b') - str.begin();
    }
    return true;
}
 
// Driver code
int main()
{
    string str = "abbaaabbabba";
    int n = str.length();
    isValidString(str, n) ? cout
                << "true" : cout << "false";
    return 0;
}
 
// This code is contributed by
// sanjeev2552

Java

// Java implementation of the approach
class GFG {
 
    // Function that returns 1 if str is valid
    private static boolean isValidString(String str, int n)
    {
 
        // Index of first appearance of 'b'
        int index = str.indexOf("b");
 
        // If str starts with 'b'
        if (index == 0)
            return false;
 
        // While 'b' occurs in str
        while (index != -1) {
 
            // If 'b' doesn't appear after an 'a'
            if (str.charAt(index - 1) != 'a')
                return false;
 
            // If 'b' is not succeeded by another 'b'
            if (index + 1 < n && str.charAt(index + 1) != 'b')
                return false;
 
            // If sub-string is of the type "abbb"
            if (index + 2 < n && str.charAt(index + 2) == 'b')
                return false;
 
            // If str ends with a single b
            if (index == n - 1)
                return false;
 
            index = str.indexOf("b", index + 2);
        }
        return true;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        String str = "abbaaabbabba";
        int n = str.length();
        System.out.println(isValidString(str, n));
    }
}

Python 3

# Python 3 implementation of the approach
 
# Function that returns 1 if str is valid
def isValidString(str, n):
 
    # Index of first appearance of 'b'
    idx = str.find("b")
 
    # If str starts with 'b'
    if (idx == 0):
        return False
 
    # While 'b' occurs in str
    while (idx != -1):
 
        # If 'b' doesn't appear after an 'a'
        if (str[idx - 1] != 'a'):
            return False
 
        # If 'b' is not succeeded by another 'b'
        if (idx + 1 < n and str[idx + 1] != 'b'):
            return False
 
        # If sub-string is of the type "abbb"
        if (idx + 2 < n and str[idx + 2] == 'b'):
            return False
 
        # If str ends with a single b
        if (idx == n - 1):
            return False
 
        idx = str.find("b", idx + 2)
 
    return True
 
# Driver code
if __name__ == "__main__":
 
    str = "abbaaabbabba"
    n = len(str)
    print(isValidString(str, n))
 
# This code is contributed by ita_c

C#

// C# implementation of the approach
using System;
 
class GFG
{
 
    // Function that returns 1 if str is valid
    private static bool isValidString(string str, int n)
    {
 
        // Index of first appearance of 'b'
        int index = str.IndexOf("b");
 
        // If str starts with 'b'
        if (index == 0)
            return false;
 
        // While 'b' occurs in str
        while (index != -1)
        {
 
            // If 'b' doesn't appear after an 'a'
            if (str[index - 1] != 'a')
                return false;
 
            // If 'b' is not succeeded by another 'b'
            if (index + 1 < n && str[index + 1] != 'b')
                return false;
 
            // If sub-string is of the type "abbb"
            if (index + 2 < n && str[index + 2] == 'b')
                return false;
 
            // If str ends with a single b
            if (index == n - 1)
                return false;
 
            index = str.IndexOf("b", index + 2);
        }
        return true;
    }
 
    // Driver code
    public static void Main()
    {
        string str = "abbaaabbabba";
        int n = str.Length;
        Console.WriteLine(isValidString(str, n));
    }
}
 
// This code is contributed by Ryuga

Javascript

<script>
// Javascript implementation of the approach
 
// Function that returns 1 if str is valid
function isValidString(str,n)
{
        // Index of first appearance of 'b'
        let index = str.indexOf("b");
   
        // If str starts with 'b'
        if (index == 0)
            return false;
   
        // While 'b' occurs in str
        while (index != -1) {
   
            // If 'b' doesn't appear after an 'a'
            if (str[index - 1] != 'a')
                return false;
   
            // If 'b' is not succeeded by another 'b'
            if (index + 1 < n && str[index + 1] != 'b')
                return false;
   
            // If sub-string is of the type "abbb"
            if (index + 2 < n && str[index + 2] == 'b')
                return false;
   
            // If str ends with a single b
            if (index == n - 1)
                return false;
   
            index = str.indexOf("b", index + 2);
        }
        return true;
}
 
// Driver code
let str = "abbaaabbabba";
let n = str.length;
document.write(isValidString(str, n));
 
// This code is contributed by rag2127
</script>
Producción: 

true

 

Publicación traducida automáticamente

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