Número mínimo de operaciones para mover todos los caracteres en mayúscula antes que todos los caracteres en minúscula

Dada una string str , que contiene caracteres en mayúsculas y minúsculas. En una sola operación, cualquier carácter en minúscula se puede convertir en un carácter en mayúscula y viceversa. La tarea es imprimir el número mínimo de tales operaciones necesarias para que la string resultante consista en cero o más caracteres en mayúscula seguidos de cero o más caracteres en minúscula.
Ejemplos: 
 

Entrada: str = “geEks” 
Salida:
Los 2 primeros caracteres se pueden convertir a caracteres en mayúsculas, es decir, “GEEks” con 2 operaciones. 
O el tercer carácter se puede convertir a un carácter en minúsculas, es decir, «geeks» con una sola operación.
Entrada: str = «geek» 
Salida:
La string ya está en el formato especificado. 
 

Enfoque: Hay dos casos posibles: 
 

  • Busque el índice del último carácter en mayúsculas de la string y convierta todos los caracteres en minúsculas que aparecen antes en caracteres en mayúsculas.
  • O busque el índice del primer carácter en minúsculas de la string y convierta todos los caracteres en mayúsculas que aparecen después en caracteres en minúsculas.

Elija el caso donde las operaciones requeridas sean mínimas.
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 minimum
// number of operations required
int minOperations(string str, int n)
{
 
    // To store the indices of the last uppercase
    // and the first lowercase character
    int i, lastUpper = -1, firstLower = -1;
 
    // Find the last uppercase character
    for (i = n - 1; i >= 0; i--)
    {
        if (isupper(str[i]))
        {
            lastUpper = i;
            break;
        }
    }
 
    // Find the first lowercase character
    for (i = 0; i < n; i++)
    {
        if (islower(str[i]))
        {
            firstLower = i;
            break;
        }
    }
 
    // If all the characters are either
    // uppercase or lowercase
    if (lastUpper == -1 || firstLower == -1)
        return 0;
 
    // Count of uppercase characters that appear
    // after the first lowercase character
    int countUpper = 0;
    for (i = firstLower; i < n; i++)
    {
        if (isupper(str[i]))
        {
            countUpper++;
        }
    }
 
    // Count of lowercase characters that appear
    // before the last uppercase character
    int countLower = 0;
    for (i = 0; i < lastUpper; i++)
    {
        if (islower(str[i]))
        {
            countLower++;
        }
    }
 
    // Return the minimum operations required
    return min(countLower, countUpper);
}
 
// Driver Code
int main()
{
    string str = "geEksFOrGEekS";
    int n = str.length();
    cout << minOperations(str, n) << endl;
}
 
// This code is contributed by
// Surendra_Gangwar

Java

// Java implementation of the approach
class GFG {
 
    // Function to return the minimum
    // number of operations required
    static int minOperations(String str, int n)
    {
 
        // To store the indices of the last uppercase
        // and the first lowercase character
        int i, lastUpper = -1, firstLower = -1;
 
        // Find the last uppercase character
        for (i = n - 1; i >= 0; i--) {
            if (Character.isUpperCase(str.charAt(i))) {
                lastUpper = i;
                break;
            }
        }
 
        // Find the first lowercase character
        for (i = 0; i < n; i++) {
            if (Character.isLowerCase(str.charAt(i))) {
                firstLower = i;
                break;
            }
        }
 
        // If all the characters are either
        // uppercase or lowercase
        if (lastUpper == -1 || firstLower == -1)
            return 0;
 
        // Count of uppercase characters that appear
        // after the first lowercase character
        int countUpper = 0;
        for (i = firstLower; i < n; i++) {
            if (Character.isUpperCase(str.charAt(i))) {
                countUpper++;
            }
        }
 
        // Count of lowercase characters that appear
        // before the last uppercase character
        int countLower = 0;
        for (i = 0; i < lastUpper; i++) {
            if (Character.isLowerCase(str.charAt(i))) {
                countLower++;
            }
        }
 
        // Return the minimum operations required
        return Math.min(countLower, countUpper);
    }
 
    // Driver Code
    public static void main(String args[])
    {
        String str = "geEksFOrGEekS";
        int n = str.length();
        System.out.println(minOperations(str, n));
    }
}

Python 3

# Python 3 implementation of the approach
 
# Function to return the minimum
# number of operations required
def minOperations(str, n):
 
    # To store the indices of the last uppercase
    # and the first lowercase character
    lastUpper = -1
    firstLower = -1
 
    # Find the last uppercase character
    for i in range( n - 1, -1, -1):
        if (str[i].isupper()):
            lastUpper = i
            break
 
    # Find the first lowercase character
    for i in range(n):
        if (str[i].islower()):
            firstLower = i
            break
 
    # If all the characters are either
    # uppercase or lowercase
    if (lastUpper == -1 or firstLower == -1):
        return 0
 
    # Count of uppercase characters that appear
    # after the first lowercase character
    countUpper = 0
    for i in range( firstLower,n):
        if (str[i].isupper()):
            countUpper += 1
 
    # Count of lowercase characters that appear
    # before the last uppercase character
    countLower = 0
    for i in range(lastUpper):
        if (str[i].islower()):
            countLower += 1
 
    # Return the minimum operations required
    return min(countLower, countUpper)
 
# Driver Code
if __name__ == "__main__":
     
    str = "geEksFOrGEekS"
    n = len(str)
    print(minOperations(str, n))
 
# This code is contributed by Ita_c.

C#

// C# implementation of the approach
using System;
 
class GFG
{
 
    // Function to return the minimum
    // number of operations required
    static int minOperations(string str, int n)
    {
 
        // To store the indices of the last uppercase
        // and the first lowercase character
        int i, lastUpper = -1, firstLower = -1;
 
        // Find the last uppercase character
        for (i = n - 1; i >= 0; i--)
        {
            if (Char.IsUpper(str[i]))
            {
                lastUpper = i;
                break;
            }
        }
 
        // Find the first lowercase character
        for (i = 0; i < n; i++)
        {
            if (Char.IsLower(str[i]))
            {
                firstLower = i;
                break;
            }
        }
 
        // If all the characters are either
        // uppercase or lowercase
        if (lastUpper == -1 || firstLower == -1)
            return 0;
 
        // Count of uppercase characters that appear
        // after the first lowercase character
        int countUpper = 0;
        for (i = firstLower; i < n; i++)
        {
            if (Char.IsUpper(str[i]))
            {
                countUpper++;
            }
        }
 
        // Count of lowercase characters that appear
        // before the last uppercase character
        int countLower = 0;
        for (i = 0; i < lastUpper; i++)
        {
            if (Char.IsLower(str[i]))
            {
                countLower++;
            }
        }
 
        // Return the minimum operations required
        return Math.Min(countLower, countUpper);
    }
 
    // Driver Code
    public static void Main()
    {
        string str = "geEksFOrGEekS";
        int n = str.Length;
        Console.WriteLine(minOperations(str, n));
    }
}
 
// This code is contributed by Ryuga

PHP

<?php
// PHP implementation of the approach
 
// Function to return the minimum
// number of operations required
function minOperations($str, $n)
{
 
    // To store the indices of the last uppercase
    // and the first lowercase character
    $i; $lastUpper = -1; $firstLower = -1;
     
    // Find the last uppercase character
    for ($i = $n - 1; $i >= 0; $i--)
    {
        if (ctype_upper($str[$i]))
        {
            $lastUpper = $i;
            break;
        }
    }
 
    // Find the first lowercase character
    for ($i = 0; $i < $n; $i++)
    {
        if (ctype_lower($str[$i]))
        {
            $firstLower = $i;
            break;
        }
    }
 
    // If all the characters are either
    // uppercase or lowercase
    if ($lastUpper == -1 || $firstLower == -1)
        return 0;
 
    // Count of uppercase characters that appear
    // after the first lowercase character
    $countUpper = 0;
    for ($i = $firstLower; $i < $n; $i++)
    {
        if (ctype_upper($str[$i]))
        {
            $countUpper++;
        }
    }
 
    // Count of lowercase characters that appear
    // before the last uppercase character
    $countLower = 0;
    for ($i = 0; $i < $lastUpper; $i++)
    {
        if (ctype_lower($str[$i]))
        {
            $countLower++;
        }
    }
 
    // Return the minimum operations required
    return min($countLower, $countUpper);
    }
 
    // Driver Code
    {
        $str = "geEksFOrGEekS";
        $n = strlen($str);
        echo(minOperations($str, $n));
    }
 
// This code is contributed by Code_Mech
?>

Javascript

<script>
      // JavaScript implementation of the approach
      //Check UpperCase
      function isupper(str) {
        return str === str.toUpperCase();
      }
      //Check UpperCase
      function islower(str) {
        return str === str.toLowerCase();
      }
 
      // Function to return the minimum
      // number of operations required
      function minOperations(str, n) {
        // To store the indices of the last uppercase
        // and the first lowercase character
        var i,
          lastUpper = -1,
          firstLower = -1;
 
        // Find the last uppercase character
        for (i = n - 1; i >= 0; i--) {
          if (isupper(str[i])) {
            lastUpper = i;
            break;
          }
        }
 
        // Find the first lowercase character
        for (i = 0; i < n; i++) {
          if (islower(str[i])) {
            firstLower = i;
            break;
          }
        }
 
        // If all the characters are either
        // uppercase or lowercase
        if (lastUpper === -1 || firstLower === -1) return 0;
 
        // Count of uppercase characters that appear
        // after the first lowercase character
        var countUpper = 0;
        for (i = firstLower; i < n; i++) {
          if (isupper(str[i])) {
            countUpper++;
          }
        }
 
        // Count of lowercase characters that appear
        // before the last uppercase character
        var countLower = 0;
        for (i = 0; i < lastUpper; i++) {
          if (islower(str[i])) {
            countLower++;
          }
        }
 
        // Return the minimum operations required
        return Math.min(countLower, countUpper);
      }
 
      // Driver Code
      var str = "geEksFOrGEekS";
      var n = str.length;
      document.write(minOperations(str, n) + "<br>");
    </script>
Producción: 

6

 

Complejidad de tiempo: O(N) donde N es la longitud de la string.
Espacio Auxiliar: O(1), ya que no se ha ocupado ningún espacio extra.

Publicación traducida automáticamente

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