Caracteres mínimos que deben insertarse de modo que no haya tres caracteres consecutivos iguales

Dada una string str y la tarea es modificar la string de modo que no haya tres caracteres consecutivos iguales. En una sola operación, se puede insertar cualquier carácter en cualquier posición de la string. Encuentre el número mínimo de tales operaciones requeridas.
Ejemplos: 
 

Entrada: str = “aabbbcc” 
Salida:
“aabb d bcc ” es la string modificada.
Entrada: str = «geeksforgeeks» 
Salida:
 

Enfoque: Por cada tres caracteres consecutivos que son iguales, se debe insertar un solo carácter entre ellos para hacer que tres caracteres consecutivos sean diferentes. Pero la cantidad de operaciones debe minimizarse, por lo que el carácter debe insertarse después del segundo carácter. Por ejemplo, si la string es «bbbb», entonces si el carácter se inserta en la segunda posición, es decir, «babbb», entonces todavía hay tres mismos caracteres consecutivos y se requiere otra operación para resolver eso, pero si el carácter se insertó en la tercera posición es decir, «bbabb», entonces solo se requiere una sola operación.
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 return the count of characters
// that are to be inserted in str such that no
// three consecutive characters are same
int getCount(string str, int n)
{
 
    // To store the count of
    // operations required
    int cnt = 0;
 
    int i = 0;
    while (i < n - 2) {
 
        // A character needs to be
        // inserted after str[i + 1]
        if (str[i] == str[i + 1]
            && str[i] == str[i + 2]) {
            cnt++;
            i = i + 2;
        }
 
        // Current three consecutive
        // characters are not same
        else
            i++;
    }
 
    return cnt;
}
 
// Driver code
int main()
{
    string str = "aabbbcc";
    int n = str.length();
 
    cout << getCount(str, n);
 
    return 0;
}

Java

// Java implementation of the approach
import java.util.*;
 
class GFG
{
     
    // Function to return the count of characters
    // that are to be inserted in str such that no
    // three consecutive characters are same
    static int getCount(char[] str, int n)
    {
 
        // To store the count of
        // operations required
        int cnt = 0;
 
        int i = 0;
        while (i < n - 2)
        {
 
            // A character needs to be
            // inserted after str[i + 1]
            if (str[i] == str[i + 1] &&
                str[i] == str[i + 2])
            {
                cnt++;
                i = i + 2;
            }
             
            // Current three consecutive
            // characters are not same
            else
            {
                i++;
            }
        }
        return cnt;
    }
 
    // Driver code
    static public void main(String[] arg)
    {
        String str = "aabbbcc";
        int n = str.length();
 
        System.out.println(getCount(str.toCharArray(), n));
    }
}
 
// This code is contributed by PrinciRaj1992

Python3

# Python3 implementation of the approach
 
# Function to return the count of characters
# that are to be inserted in str1 such that no
# three consecutive characters are same
def getCount(str1, n):
 
    # To store the count of
    # operations required
    cnt = 0;
 
    i = 0;
    while (i < n - 2):
 
        # A character needs to be
        # inserted after str1[i + 1]
        if (str1[i] == str1[i + 1] and
            str1[i] == str1[i + 2]):
            cnt += 1
            i = i + 2
 
        # Current three consecutive
        # characters are not same
        else:
            i += 1
 
    return cnt
 
# Driver code
str1 = "aabbbcc"
n = len(str1)
 
print(getCount(str1, n))
 
# This code is contributed by Mohit Kumar

C#

// C# implementation of the above approach
using System;
 
class GFG
{
     
    // Function to return the count of characters
    // that are to be inserted in str such that no
    // three consecutive characters are same
    static int getCount(string str, int n)
    {
 
        // To store the count of
        // operations required
        int cnt = 0;
 
        int i = 0;
        while (i < n - 2)
        {
 
            // A character needs to be
            // inserted after str[i + 1]
            if (str[i] == str[i + 1] &&
                str[i] == str[i + 2])
            {
                cnt++;
                i = i + 2;
            }
             
            // Current three consecutive
            // characters are not same
            else
            {
                i++;
            }
        }
        return cnt;
    }
 
    // Driver code
    static public void Main ()
    {
        string str = "aabbbcc";
        int n = str.Length;
 
        Console.WriteLine(getCount(str, n));
    }
}
 
// This code is contributed by AnkitRai01

Javascript

<script>
      // JavaScript implementation of the above approach
      // Function to return the count of characters
      // that are to be inserted in str such that no
      // three consecutive characters are same
      function getCount(str, n) {
        // To store the count of
        // operations required
        var cnt = 0;
 
        var i = 0;
        while (i < n - 2) {
          // A character needs to be
          // inserted after str[i + 1]
          if (str[i] === str[i + 1] && str[i] === str[i + 2]) {
            cnt++;
            i = i + 2;
          }
 
          // Current three consecutive
          // characters are not same
          else {
            i++;
          }
        }
        return cnt;
      }
 
      // Driver code
      var str = "aabbbcc";
      var n = str.length;
 
      document.write(getCount(str, n));
    </script>
Producción: 

1

 

Publicación traducida automáticamente

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