Haga que todos los caracteres en la string dada sean iguales cambiando la vocal a consonante y viceversa

Dada una string str que contiene caracteres en minúsculas, la tarea es encontrar el número mínimo de operaciones necesarias para que todos los caracteres sean iguales. En una operación, cualquier consonante se puede convertir en cualquier vocal o cualquier vocal se puede convertir en cualquier consonante.

Ejemplos:

Entrada: str = “banana”
Salida: 3
Explicación: Convierte todas las consonantes al carácter de vocal A

Entrada: str = «hexon»
Salida: 5
Explicación: Convierta E en O primero y luego todas las consonantes en Alfabeto O

 

Enfoque: El problema básico aquí es que:

  • Las operaciones necesarias para cambiar una consonante por otra consonante o una vocal por otra vocal: 2 Operación
  • La operación requerida para cambiar una consonante a vocal o una vocal a consonante: 1 Operación

Entonces, está claro que es más económico cambiar una consonante por una vocal o una vocal por una consonante que cambiar una consonante por otra consonante o una vocal por otra vocal.

Ahora para resolver esta pregunta, siga los pasos a continuación:

  1. Calcula la frecuencia de todos los caracteres y encuentra la consonante y vocal de mayor frecuencia, digamos A y B respectivamente.
  2. Intente cambiar todos los caracteres a A y B y almacene las operaciones requeridas en las variables minA y minB respectivamente.
  3. Mínimo de minA y minB es la respuesta a este problema.

A continuación se muestra la implementación del enfoque anterior.

C++

// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the minimum operations
// required to make all string characters equal
int minOperations(string str)
{
    int n = str.size();
 
    // Vector to store the
    // frequency of all characters
    vector<int> freq(26, 0);
 
    for (auto x : str) {
        freq[x - 'a']++;
    }
 
    int mxA = INT_MIN, mxB = INT_MIN;
 
    // Variables to store
    // consonant and vowel
    // with highest frequency
    char A, B;
 
    vector<char> vowels
        = { 'a', 'e', 'i', 'o', 'u' };
 
    for (int i = 0; i < 26; ++i) {
        bool isVowel = 0;
        for (auto x : vowels) {
            if ('a' + i == x) {
                isVowel = 1;
                break;
            }
        }
 
        // If current character is a vowel
        if (isVowel) {
            if (mxB < freq[i]) {
                mxB = freq[i];
                B = 'a' + i;
            }
        }
 
        // If current character is a consonant
        else {
            if (mxA < freq[i]) {
                mxA = freq[i];
                A = 'a' + i;
            }
        }
    }
 
    int minA = 0, minB = 0;
    for (auto x : str) {
        bool isVowel = 0;
        for (auto y : vowels) {
            if (x == y) {
                isVowel = 1;
                break;
            }
        }
 
        // If current character is a vowel
        if (isVowel) {
            if (x != B) {
                minB += 2;
            }
            minA += 1;
        }
 
        // If currenct character is a
        // consonant
        else {
            if (x != A) {
                minA += 2;
            }
            minB += 1;
        }
    }
 
    // If no vowel exists
    if (mxB == INT_MIN) {
        return minA;
    }
 
    // If no consonant exists
    if (mxA == INT_MIN) {
        return minB;
    }
 
    // Returning minimum of the two
    return min(minA, minB);
}
 
// Driver Code
int main()
{
    string str = "hexon";
    cout << minOperations(str);
}

Java

// Java program for the above approach
import java.util.*;
public class GFG {
 
    // Function to return the minimum operations
    // required to make all string characters equal
    static int minOperations(String str)
    {
        int n = str.length();
 
        // Vector to store the
        // frequency of all characters
        char[] freq = new char[26];
 
        for(char x : str.toCharArray()) { freq[x - 'a']++; }
 
        int mxA = Integer.MIN_VALUE, mxB = Integer.MIN_VALUE;
 
        // Variables to store
        // consonant and vowel
        // with highest frequency
        char A = ' ', B = ' ';
 
        char[] vowels = { 'a', 'e', 'i', 'o', 'u' };
 
        for (int i = 0; i < 26; ++i) {
            int isVowel = 0;
            for(char x : vowels)
            {
                if ('a' + i == x) {
                    isVowel = 1;
                    break;
                }
            }
 
            // If current character is a vowel
            if (isVowel > 0) {
                if (mxB < freq[i]) {
                    mxB = freq[i];
                    B = (char)(97 + i);
                }
            }
 
            // If current character is a consonant
            else {
                if (mxA < freq[i]) {
                    mxA = freq[i];
                    A = (char)(97 + i);
                }
            }
        }
 
        int minA = 0, minB = 0;
        for(char x : str.toCharArray())
        {
            int isVowel = 0;
            for(char y : vowels)
            {
                if (x == y) {
                    isVowel = 1;
                    break;
                }
            }
 
            // If current character is a vowel
            if (isVowel > 0) {
                if (x != B) {
                    minB += 2;
                }
                minA += 1;
            }
 
            // If currenct character is a
            // consonant
            else {
                if (x != A) {
                    minA += 2;
                }
                minB += 1;
            }
        }
 
        // If no vowel exists
        if (mxB == Integer.MIN_VALUE) {
            return minA;
        }
 
        // If no consonant exists
        if (mxA == Integer.MIN_VALUE) {
            return minB;
        }
 
        // Returning minimum of the two
        return Math.min(minA, minB);
    }
 
    // Driver Code
    public static void main(String args[])
    {
        String str = "hexon";
        System.out.println(minOperations(str));
    }
}
 
// This code is contributed by Samim Hossain Mondal.

Python3

# python program for the above approach
INT_MIN = -2147483647 - 1
 
# Function to return the minimum operations
# required to make all string characters equal
def minOperations(str):
 
    n = len(str)
 
    # Vector to store the
    # frequency of all characters
    freq = [0 for _ in range(26)]
 
    for x in str:
        freq[ord(x) - ord('a')] += 1
 
    mxA = INT_MIN
    mxB = INT_MIN
 
    # Variables to store
    # consonant and vowel
    # with highest frequency
    A = ''
    B = ''
 
    vowels = ['a', 'e', 'i', 'o', 'u']
 
    for i in range(0, 26):
        isVowel = 0
 
        for x in vowels:
            if (ord('a') + i == ord(x)):
                isVowel = 1
                break
 
        # If current character is a vowel
        if (isVowel):
            if (mxB < freq[i]):
                mxB = freq[i]
                B = chr(ord('a') + i)
 
        # If current character is a consonant
        else:
            if (mxA < freq[i]):
                mxA = freq[i]
                A = chr(ord('a') + i)
 
    minA = 0
    minB = 0
    for x in str:
        isVowel = 0
        for y in vowels:
            if (x == y):
                isVowel = 1
                break
 
        # If current character is a vowel
        if (isVowel):
            if (x != B):
                minB += 2
            minA += 1
 
            # If currenct character is a
            # consonant
        else:
            if (x != A):
                minA += 2
            minB += 1
 
        # If no vowel exists
    if (mxB == INT_MIN):
        return minA
 
        # If no consonant exists
    if (mxA == INT_MIN):
        return minB
 
        # Returning minimum of the two
    return min(minA, minB)
 
# Driver Code
if __name__ == "__main__":
 
    str = "hexon"
    print(minOperations(str))
 
    # This code is contributed by rakeshsahni

C#

// C# program for the above approach
using System;
class GFG {
 
    // Function to return the minimum operations
    // required to make all string characters equal
    static int minOperations(string str)
    {
        int n = str.Length;
 
        // Vector to store the
        // frequency of all characters
        char[] freq = new char[26];
 
        foreach(char x in str) { freq[x - 'a']++; }
 
        int mxA = Int32.MinValue, mxB = Int32.MinValue;
 
        // Variables to store
        // consonant and vowel
        // with highest frequency
        char A = ' ', B = ' ';
 
        char[] vowels = { 'a', 'e', 'i', 'o', 'u' };
 
        for (int i = 0; i < 26; ++i) {
            int isVowel = 0;
            foreach(char x in vowels)
            {
                if ('a' + i == x) {
                    isVowel = 1;
                    break;
                }
            }
 
            // If current character is a vowel
            if (isVowel > 0) {
                if (mxB < freq[i]) {
                    mxB = freq[i];
                    B = (char)(97 + i);
                }
            }
 
            // If current character is a consonant
            else {
                if (mxA < freq[i]) {
                    mxA = freq[i];
                    A = (char)(97 + i);
                }
            }
        }
 
        int minA = 0, minB = 0;
        foreach(char x in str)
        {
            int isVowel = 0;
            foreach(char y in vowels)
            {
                if (x == y) {
                    isVowel = 1;
                    break;
                }
            }
 
            // If current character is a vowel
            if (isVowel > 0) {
                if (x != B) {
                    minB += 2;
                }
                minA += 1;
            }
 
            // If currenct character is a
            // consonant
            else {
                if (x != A) {
                    minA += 2;
                }
                minB += 1;
            }
        }
 
        // If no vowel exists
        if (mxB == Int32.MinValue) {
            return minA;
        }
 
        // If no consonant exists
        if (mxA == Int32.MinValue) {
            return minB;
        }
 
        // Returning minimum of the two
        return Math.Min(minA, minB);
    }
 
    // Driver Code
    public static void Main()
    {
        string str = "hexon";
        Console.WriteLine(minOperations(str));
    }
}
 
// This code is contributed by ukasp.

Javascript

<script>
// Javascript program for the above approach
 
// Function to return the minimum operations
// required to make all string characters equal
function minOperations(str) {
  let n = str.length;
 
  // Vector to store the
  // frequency of all characters
  let freq = new Array(26).fill(0);
 
  for (x of str) {
    freq[x.charCodeAt(0) - 'a'.charCodeAt(0)]++;
  }
 
  let mxA = Number.MIN_SAFE_INTEGER, mxB = Number.MIN_SAFE_INTEGER;
 
  // Variables to store
  // consonant and vowel
  // with highest frequency
  let A = "", B = "";
 
  let vowels = ['a', 'e', 'i', 'o', 'u'];
 
  for (let i = 0; i < 26; ++i) {
    let isVowel = 0;
    for (x of vowels) {
      if ('a'.charCodeAt(0) + i == x.charCodeAt(0)) {
        isVowel = 1;
        break;
      }
    }
 
    // If current character is a vowel
    if (isVowel) {
      if (mxB < freq[i]) {
        mxB = freq[i];
        B = String.fromCharCode('a'.charCodeAt(0) + i);
      }
    }
 
    // If current character is a consonant
    else {
      if (mxA < freq[i]) {
        mxA = freq[i];
        A = String.fromCharCode('a'.charCodeAt(0) + i);
      }
    }
  }
 
  let minA = 0, minB = 0;
  for (x of str) {
    let isVowel = 0;
    for (y of vowels) {
      if (x == y) {
        isVowel = 1;
        break;
      }
    }
 
    // If current character is a vowel
    if (isVowel) {
      if (x != B) {
        minB += 2;
      }
      minA += 1;
    }
 
    // If currenct character is a
    // consonant
    else {
      if (x != A) {
        minA += 2;
      }
      minB += 1;
    }
  }
 
  // If no vowel exists
  if (mxB == Number.MIN_SAFE_INTEGER) {
    return minA;
  }
 
  // If no consonant exists
  if (mxA == Number.MIN_SAFE_INTEGER) {
    return minB;
  }
 
  // Returning minimum of the two
  return Math.min(minA, minB);
}
 
// Driver Cod
 
let str = "hexon";
document.write(minOperations(str))
 
// This code is contributed by saurabh_jaiswal.
</script>
Producción

5

Complejidad temporal: O(N)
Espacio auxiliar: O(1)

Publicación traducida automáticamente

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