Compruebe si cada grupo de a va seguido de un grupo de b de la misma longitud

Dada la string str , la tarea es verificar si cada grupo de aes consecutivos es seguido por un grupo de bs consecutivos de la misma longitud. Si la condición es verdadera para cada grupo, imprima 1 ; de lo contrario, imprima 0 .
Ejemplos: 
 

Entrada: str = “ababaabb” 
Salida:
ab, ab, aabb. Todos los grupos son válidos
Entrada: str = “aabbabb” 
Salida:
aabb, abb (Una sola ‘a’ seguida de 2 ‘b’) 
 

Acercarse: 

  • Por cada a en la string, incremente el conteo .
  • A partir de la primera b , disminuya la cuenta para cada b .
  • Si al final del ciclo anterior, count != 0 , devuelve false .
  • De lo contrario, repita los dos primeros pasos para el resto de la string.
  • Devuelve verdadero si la condición se cumple para todos los ciclos, de lo contrario imprime 0 .

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 to match whether there are always n consecutive b's
// followed by n consecutive a's throughout the string
int matchPattern(string s)
{
    int count = 0;
    int n = s.length();
 
    // Traverse through the string
    int i = 0;
    while (i < n) {
 
        // Count a's in current segment
        while (i < n && s[i] == 'a') {
            count++;
            i++;
        }
 
        // Count b's in current segment
        while (i < n && s[i] == 'b') {
            count--;
            i++;
        }
 
        // If both counts are not same.
        if (count != 0)
            return false;
    }
 
    return true;
}
 
// Driver code
int main()
{
    string s = "bb";
    if (matchPattern(s) == true)
        cout << "Yes";
    else
        cout << "No";
    return 0;
}

Java

// Java implementation of the above approach
 
public class GFG{
 
// Function to match whether there are always n consecutive b's
// followed by n consecutive a's throughout the string
static boolean matchPattern(String s)
{
    int count = 0;
    int n = s.length();
 
    // Traverse through the string
    int i = 0;
    while (i < n) {
 
        // Count a's in current segment
        while (i < n && s.charAt(i) == 'a') {
            count++;
            i++;
        }
 
        // Count b's in current segment
        while (i < n && s.charAt(i) == 'b') {
            count--;
            i++;
        }
 
        // If both counts are not same.
        if (count != 0)
            return false;
    }
 
    return true;
}
 
// Driver code
public static void main(String []args)
{
    String s = "bb";
    if (matchPattern(s) == true)
        System.out.println("Yes");
    else
        System.out.println("No");
}
 
// This code is contributed by Ryuga
}

Python3

# Python 3 implementation of the approach
 
# Function to match whether there are
# always n consecutive b's followed by
# n consecutive a's throughout the string
def matchPattern(s):
 
    count = 0;
    n = len(s);
 
    # Traverse through the string
    i = 0;
    while (i < n) :
 
        # Count a's in current segment
        while (i < n and s[i] == 'a'):
 
            count += 1 ;
            i =+ 1;
 
        # Count b's in current segment
        while (i < n and s[i] == 'b'):
            count -= 1 ;
            i += 1;
     
        # If both counts are not same.
        if (count != 0):
            return False;
 
    return True;
 
# Driver code
s = "bb";
if (matchPattern(s) == True):
    print("Yes");
else:
    print("No");
 
# This code is contributed
# by Akanksha Rai

C#

// C# implementation of the above approach
  
using System;
public class GFG{
  
// Function to match whether there are always n consecutive b's
// followed by n consecutive a's throughout the string
static bool matchPattern(string s)
{
    int count = 0;
    int n = s.Length;
  
    // Traverse through the string
    int i = 0;
    while (i < n) {
  
        // Count a's in current segment
        while (i < n && s[i] == 'a') {
            count++;
            i++;
        }
  
        // Count b's in current segment
        while (i < n && s[i] == 'b') {
            count--;
            i++;
        }
  
        // If both counts are not same.
        if (count != 0)
            return false;
    }
  
    return true;
}
  
// Driver code
public static void Main()
{
    string s = "bb";
    if (matchPattern(s) == true)
        Console.Write("Yes");
    else
        Console.Write("No");
}
 
}

PHP

<?php
//PHP implementation of the approach
 
// Function to match whether there are always n consecutive b's
// followed by n consecutive a's throughout the string
function  matchPattern($s)
{
    $count = 0;
    $n = strlen($s);
 
    // Traverse through the string
    $i = 0;
    while ($i < $n) {
 
        // Count a's in current segment
        while ($i < $n && $s[$i] == 'a') {
            $count++;
            $i++;
        }
 
        // Count b's in current segment
        while ($i < $n && $s[$i] == 'b') {
            $count--;
            $i++;
        }
 
        // If both counts are not same.
        if ($count != 0)
            return false;
    }
 
    return true;
}
 
// Driver code
  
    $s = "bb";
    if (matchPattern($s) == true)
        echo  "Yes";
    else
        echo "No";
     
 
// This code is contributed by ajit
?>

Javascript

<script>
 
    // Javascript implementation of
    // the above approach
     
    // Function to match whether there are
    // always n consecutive b's
    // followed by n consecutive a's
    // throughout the string
    function matchPattern(s)
    {
        let count = 0;
        let n = s.length;
 
        // Traverse through the string
        let i = 0;
        while (i < n)
        {
 
            // Count a's in current segment
            while (i < n && s[i] == 'a')
            {
                count++;
                i++;
            }
 
            // Count b's in current segment
            while (i < n && s[i] == 'b')
            {
                count--;
                i++;
            }
 
            // If both counts are not same.
            if (count != 0)
                return false;
        }
 
        return true;
    }
     
    let s = "bb";
    if (matchPattern(s) == true)
        document.write("Yes");
    else
        document.write("No");
     
</script>
Producción: 

No

 

Complejidad de tiempo : O( | s | ) ,donde | s | es la longitud de la string dada s.

Complejidad espacial: O (1), ya que no estamos usando ningún espacio adicional

Publicación traducida automáticamente

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