Imprime la frecuencia de cada carácter en orden alfabético

Dada una string str , la tarea es imprimir la frecuencia de cada uno de los caracteres de str en orden alfabético.
Ejemplo: 
 

Entrada: str = “aabccccddd” 
Salida: a2b1c4d3 
Como ya está en orden alfabético, 
se devuelve la frecuencia de los caracteres para cada carácter. 
Entrada: str = «geeksforgeeks» 
Salida: e4f1g2k2o1r1s2 
 

Acercarse: 
 

  1. Cree un Mapa para almacenar la frecuencia de cada uno de los caracteres de la string dada.
  2. Iterar a través de la string y verificar si el carácter está presente en el mapa.
  3. Si el carácter no está presente, insértelo en el mapa con 1 como valor inicial; de lo contrario, incremente su frecuencia en 1.
  4. Finalmente, imprima la frecuencia de cada uno de los caracteres en orden alfabético.

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

C++

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
const int MAX = 26;
 
// Function to print the frequency
// of each of the characters of
// s in alphabetical order
void compressString(string s, int n)
{
    // To store the frequency
    // of the characters
    int freq[MAX] = { 0 };
 
    // Update the frequency array
    for (int i = 0; i < n; i++) {
        freq[s[i] - 'a']++;
    }
 
    // Print the frequency in alphatecial order
    for (int i = 0; i < MAX; i++) {
 
        // If the current alphabet doesn't
        // appear in the string
        if (freq[i] == 0)
            continue;
 
        cout << (char)(i + 'a') << freq[i];
    }
}
 
// Driver code
int main()
{
    string s = "geeksforgeeks";
    int n = s.length();
 
    compressString(s, n);
 
    return 0;
}

Java

// Java implementation of the approach
class GFG
{
     
    static int MAX = 26;
     
    // Function to print the frequency
    // of each of the characters of
    // s in alphabetical order
    static void compressString(String s, int n)
    {
        // To store the frequency
        // of the characters
        int freq[] = new int[MAX] ;
     
        // Update the frequency array
        for (int i = 0; i < n; i++)
        {
            freq[s.charAt(i) - 'a']++;
        }
     
        // Print the frequency in alphatecial order
        for (int i = 0; i < MAX; i++)
        {
     
            // If the current alphabet doesn't
            // appear in the string
            if (freq[i] == 0)
                continue;
     
            System.out.print((char)(i + 'a') +""+ freq[i]);
        }
    }
     
    // Driver code
    public static void main (String[] args)
    {
        String s = "geeksforgeeks";
        int n = s.length();
     
        compressString(s, n);
    }
}
 
// This code is contributed by AnkitRai01

Python3

# Python3 implementation of the approach
MAX = 26;
 
# Function to print the frequency
# of each of the characters of
# s in alphabetical order
def compressString(s, n) :
 
    # To store the frequency
    # of the characters
    freq = [ 0 ] * MAX;
 
    # Update the frequency array
    for i in range(n) :
        freq[ord(s[i]) - ord('a')] += 1;
 
    # Print the frequency in alphatecial order
    for i in range(MAX) :
 
        # If the current alphabet doesn't
        # appear in the string
        if (freq[i] == 0) :
            continue;
 
        print((chr)(i + ord('a')),freq[i],end = " ");
 
# Driver code
if __name__ == "__main__" :
 
    s = "geeksforgeeks";
    n = len(s);
 
    compressString(s, n);
 
# This code is contributed by AnkitRai01

C#

// C# implementation of the approach
using System;
 
class GFG
{
     
    static int MAX = 26;
     
    // Function to print the frequency
    // of each of the characters of
    // s in alphabetical order
    static void compressString(string s, int n)
    {
        // To store the frequency
        // of the characters
        int []freq = new int[MAX] ;
     
        // Update the frequency array
        for (int i = 0; i < n; i++)
        {
            freq[s[i] - 'a']++;
        }
     
        // Print the frequency in alphatecial order
        for (int i = 0; i < MAX; i++)
        {
     
            // If the current alphabet doesn't
            // appear in the string
            if (freq[i] == 0)
                continue;
     
            Console.Write((char)(i + 'a') +""+ freq[i]);
        }
    }
     
    // Driver code
    public static void Main()
    {
        string s = "geeksforgeeks";
        int n = s.Length;
     
        compressString(s, n);
    }
}
 
// This code is contributed by AnkitRai01

Javascript

<script>
 
    // Javascript implementation of the approach
     
    let MAX = 26;
       
    // Function to print the frequency
    // of each of the characters of
    // s in alphabetical order
    function compressString(s, n)
    {
        // To store the frequency
        // of the characters
        let freq = new Array(MAX);
        freq.fill(0);
       
        // Update the frequency array
        for (let i = 0; i < n; i++)
        {
            freq[s[i].charCodeAt() - 'a'.charCodeAt()]++;
        }
       
        // Print the frequency in alphatecial order
        for (let i = 0; i < MAX; i++)
        {
       
            // If the current alphabet doesn't
            // appear in the string
            if (freq[i] == 0)
                continue;
       
            document.write(String.fromCharCode(i +
            'a'.charCodeAt()) +""+ freq[i]);
        }
    }
     
    let s = "geeksforgeeks";
    let n = s.length;
 
    compressString(s, n);
     
</script>
Producción: 

e4f1g2k2o1r1s2

 

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

Publicación traducida automáticamente

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