Dada una string str , la tarea es hacer que la string esté vacía con la operación dada. En una sola operación, puede seleccionar algunos caracteres de la string (cada uno de los caracteres seleccionados debe tener la misma frecuencia) y eliminarlos de la string. Imprime el total de operaciones requeridas para dejar la string vacía.
Ejemplos:
Entrada: str = “aabbccc”
Salida: 2
En una sola operación, los caracteres ‘a’ y ‘b’ pueden eliminarse ya que ambos tienen la misma frecuencia.
La segunda operación puede eliminar el carácter ‘c’ que tiene una frecuencia de 3.
Se requieren 2 operaciones en total.
Entrada: str = «geeksforgeeks»
Salida: 3
Enfoque: encuentre frecuencias únicas de los caracteres de la string. El recuento total de frecuencias únicas será el número de operaciones necesarias para que la string quede vacía.
Para str = “aaabbbcccc” , las frecuencias únicas son 3 y 4 . El recuento total de frecuencias únicas es 2 .
HashMap se puede usar para almacenar los caracteres y sus frecuencias, luego HashSet se puede usar para encontrar el recuento de frecuencias únicas, que es la cantidad de operaciones requeridas.
A continuación se muestra la implementación del enfoque anterior:
C++
// CPP implementation of the approach #include <bits/stdc++.h> using namespace std; // Function to return the count of operations required int totalOperations(string str, int len) { // HashMap to store characters and their frequencies unordered_map<char, int> h; for (int i = 0; i < len; i++) // If already contains the character then // increment its frequency by 1 h[str[i]]++; // HashSet to store unique frequency unordered_set<int> hs; // Insert frequencies into HashSet for (auto i : h) hs.insert(i.second); // Count of unique frequencies return hs.size(); } // Driver Code int main() { string str = "geeksforgeeks"; int len = str.length(); cout << totalOperations(str, len) << endl; return 0; } // This code is contributed by // sanjeev2552
Java
// Java implementation of the approach import java.util.*; class GFG { // Function to return the count of operations required static int totalOperations(String str, int len) { // HashMap to store characters and their frequencies HashMap<Character, Integer> h = new HashMap<Character, Integer>(); for (int i = 0; i < len; i++) { // If already contains the character then // increment its frequency by 1 if (h.containsKey(str.charAt(i))) h.put(str.charAt(i), h.get(str.charAt(i)) + 1); // Else add the character to the HashMap with frequency 1 else h.put(str.charAt(i), 1); } // Set to iterate over HashMap Set<Map.Entry<Character, Integer> > set = h.entrySet(); // HashSet to store unique frequency HashSet<Integer> hs = new HashSet<Integer>(); // Insert frequencies into HashSet for (Map.Entry<Character, Integer> me : set) hs.add(me.getValue()); // Count of unique frequencies return hs.size(); } // Driver code public static void main(String[] args) { String str = "geeksforgeeks"; int len = str.length(); System.out.println(totalOperations(str, len)); } }
Python3
# Python implementation of the approach # Function to return the count of operations required def totalOperations(st, length): # Dictionary to store characters and their frequencies d = {} for i in range(length): # If already contains the character then # increment its frequency by 1 if st[i] in d: d[st[i]] += 1 # Else add the character to the HashMap with frequency 1 else: d[st[i]] = 1 # Set to Store unique frequency valueSet = set() # Insert frequencies into HashSet for key in d.keys(): valueSet.add(d[key]) # Count of unique frequencies return len(valueSet) # Driver Code st = "geeksforgeeks" l = len(st) print(totalOperations(st, l)) # This code is contributed by Vivekkumar Singh
C#
// C# implementation of the approach using System; using System.Collections.Generic; class GFG { // Function to return // the count of operations required static int totalOperations(String str, int len) { // HashMap to store characters // and their frequencies Dictionary<char, int> h = new Dictionary<char, int>(); for (int i = 0; i < len; i++) { // If already contains the character then // increment its frequency by 1 if (h.ContainsKey(str[i])) h[str[i]] = h[str[i]] + 1; // Else add the character // to the HashMap with frequency 1 else h.Add(str[i], 1); } // Set to iterate over HashMap // HashSet to store unique frequency HashSet<int> hs = new HashSet<int>(); // Insert frequencies into HashSet foreach(KeyValuePair<char, int> me in h) hs.Add(me.Value); // Count of unique frequencies return hs.Count; } // Driver code public static void Main(String[] args) { String str = "geeksforgeeks"; int len = str.Length; Console.WriteLine(totalOperations(str, len)); } } // This code is contributed by Rajput-Ji
Javascript
<script> // Javascript implementation of the approach // Function to return the count of operations required function totalOperations(str, len) { // HashMap to store characters and their frequencies var h = new Map(); for (var i = 0; i < len; i++) // If already contains the character then // increment its frequency by 1 if(h.has(str[i])) h.set(str[i], h.get(str[i])+1) else h.set(str[i], 1) // HashSet to store unique frequency var hs = new Set(); // Insert frequencies into HashSet h.forEach((value, key) => { hs.add(value); }); // Count of unique frequencies return hs.size; } // Driver Code var str = "geeksforgeeks"; var len = str.length; document.write( totalOperations(str, len)); // This code is contributed by itsok. </script>
3
Complejidad temporal: O(n)
Espacio Auxiliar: O(n)
Publicación traducida automáticamente
Artículo escrito por Divyank_Sheth y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA