📜  按频率降序打印字符

📅  最后修改于: 2022-05-13 01:57:06.865000             🧑  作者: Mango

按频率降序打印字符

给定字符串str ,任务是按频率降序打印字符。如果两个字符的频率相同,则按字母降序对它们进行排序。
例子:

方法一:

  • 使用 unordered_map 存储给定字符串的所有元素的频率。
  • 从地图中找到最大频率元素,将其与其频率一起打印,然后将其从地图中删除。
  • 在地图不为空时重复上一步。

下面是上述方法的实现:

CPP
// C++ implementation of the approach
#include 
using namespace std;
 
// Function to print the characters
// of the given string in decreasing
// order of their frequencies
void printChar(string str, int len)
{
 
    // To store the
    unordered_map occ;
    for (int i = 0; i < len; i++)
        occ[str[i]]++;
 
    // Map's size
    int size = occ.size();
    unordered_map::iterator it;
 
    // While there are elements in the map
    while (size--) {
 
        // Finding the maximum value
        // from the map
        unsigned currentMax = 0;
        char arg_max;
        for (it = occ.begin(); it != occ.end(); ++it) {
            if (it->second > currentMax
                || (it->second == currentMax
                    && it->first > arg_max)) {
                arg_max = it->first;
                currentMax = it->second;
            }
        }
 
        // Print the character
        // alongwith its frequency
        cout << arg_max << " - " << currentMax << endl;
 
        // Delete the maximum value
        occ.erase(arg_max);
    }
}
 
// Driver code
int main()
{
 
    string str = "geeksforgeeks";
    int len = str.length();
 
    printChar(str, len);
 
    return 0;
}


Java
// Java implementation of the approach
import java.util.*;
class GFG{
 
// Function to print the characters
// of the given String in decreasing
// order of their frequencies
static void printChar(char []arr, int len)
{
 
    // To store the
    HashMap occ = new HashMap();
    for (int i = 0; i < len; i++)
        if(occ.containsKey(arr[i]))
        {
            occ.put(arr[i], occ.get(arr[i]) + 1);
        }
          else
        {
            occ.put(arr[i], 1);
        }
 
    // Map's size
    int size = occ.size();
 
    // While there are elements in the map
    while (size-- > 0)
    {
 
        // Finding the maximum value
        // from the map
        int currentMax = 0;
        char arg_max = 0;
        for (Map.Entry it : occ.entrySet())
        {
            if (it.getValue() > currentMax ||
               (it.getValue() == currentMax &&
                it.getKey() > arg_max))
            {
                arg_max = it.getKey();
                currentMax = it.getValue();
            }
        }
 
        // Print the character
        // alongwith its frequency
        System.out.print(arg_max + " - " +
                         currentMax + "\n");
 
        // Delete the maximum value
        occ.remove(arg_max);
    }
}
 
// Driver code
public static void main(String[] args)
{
    String str = "geeksforgeeks";
    int len = str.length();
 
    printChar(str.toCharArray(), len);
}
}
 
// This code is contributed by gauravrajput1


C#
// C# implementation of the approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to print the characters
// of the given String in decreasing
// order of their frequencies
static void printChar(char []arr, int len)
{
 
    // To store the
    Dictionary occ = new Dictionary();
    for (int i = 0; i < len; i++)
        if(occ.ContainsKey(arr[i]))
        {
            occ[arr[i]]  = occ[arr[i]] + 1;
        }
          else
        {
            occ.Add(arr[i], 1);
        }
 
    // Map's size
    int size = occ.Count;
 
    // While there are elements in the map
    while (size-- > 0)
    {
 
        // Finding the maximum value
        // from the map
        int currentMax = 0;
        char arg_max = (char)0;
        foreach (KeyValuePair it in occ)
        {
            if (it.Value > currentMax ||
               (it.Value == currentMax &&
                it.Key > arg_max))
            {
                arg_max = it.Key;
                currentMax = it.Value;
            }
        }
 
        // Print the character
        // alongwith its frequency
        Console.Write(arg_max + " - " +
                      currentMax + "\n");
 
        // Delete the maximum value
        occ.Remove(arg_max);
    }
}
 
// Driver code
public static void Main(String[] args)
{
    String str = "geeksforgeeks";
    int len = str.Length;
 
    printChar(str.ToCharArray(), len);
}
}
 
// This code is contributed by Princi Singh


Javascript


Java
// Java implementation of above approach
import java.util.*;
 
class GFG {
    // Driver Code
    public static void main(String[] args)
    {
        String str = "geeksforgeeks";
        printChar(str);
    }
    @SuppressWarnings("unchecked")
    // Function to print the characters
    // of the given string in decreasing
    // order of their frequencies
    public static void printChar(String str)
    {
        // Initializing array of List type.
        List[] arr = new List[str.length() + 1];
        for (int i = 0; i <= str.length(); i++) {
            // Initializing List of type Character.
            arr[i] = new ArrayList<>();
        }
        int[] freq = new int[256];
        // Mapking frequency map
        for (int i = 0; i < str.length(); i++) {
            freq[(char)str.charAt(i)]++;
        }
        // Traversing frequency array
        for (int i = 0; i < 256; i++) {
            if (freq[i] > 0) {
                // If frequency array is greater than zero
                // then storing its character on
                // i-th(frequency of that character) index
                // of arr
                arr[freq[i]].add(0, (char)(i));
            }
        }
        // Traversing arr from backwards as we need greater
        // frequency character first
        for (int i = arr.length - 1; i >= 0; i--) {
            if (!arr[i].isEmpty()) {
                for (char ch : arr[i]) {
                    System.out.println(ch + "-" + i);
                }
            }
        }
    }
}


输出
e - 4
s - 2
k - 2
g - 2
r - 1
o - 1
f - 1

方法 2:我们将创建一个大小比给定字符串长度大一的数组arr ,我们将在其中存储频率等于arr索引的字符列表,并按照以下步骤操作:

  • 使用给定字符串中存在的字符数组制作频率图。
  • 遍历频率数组,如果它的值大于零,假设k。
  • arr的第 k 个索引上,它的字符值存储在索引 0 的 List 中(因为如果频率相同,我们需要字母降序排列)。
  • 如果该索引处的 List 不为空,则从向后遍历arr因为我们首先需要更大的频率,而不是打印它的频率和字符。

上述方法的实施:

Java

// Java implementation of above approach
import java.util.*;
 
class GFG {
    // Driver Code
    public static void main(String[] args)
    {
        String str = "geeksforgeeks";
        printChar(str);
    }
    @SuppressWarnings("unchecked")
    // Function to print the characters
    // of the given string in decreasing
    // order of their frequencies
    public static void printChar(String str)
    {
        // Initializing array of List type.
        List[] arr = new List[str.length() + 1];
        for (int i = 0; i <= str.length(); i++) {
            // Initializing List of type Character.
            arr[i] = new ArrayList<>();
        }
        int[] freq = new int[256];
        // Mapking frequency map
        for (int i = 0; i < str.length(); i++) {
            freq[(char)str.charAt(i)]++;
        }
        // Traversing frequency array
        for (int i = 0; i < 256; i++) {
            if (freq[i] > 0) {
                // If frequency array is greater than zero
                // then storing its character on
                // i-th(frequency of that character) index
                // of arr
                arr[freq[i]].add(0, (char)(i));
            }
        }
        // Traversing arr from backwards as we need greater
        // frequency character first
        for (int i = arr.length - 1; i >= 0; i--) {
            if (!arr[i].isEmpty()) {
                for (char ch : arr[i]) {
                    System.out.println(ch + "-" + i);
                }
            }
        }
    }
}
输出
e-4
s-2
k-2
g-2
r-1
o-1
f-1

时间复杂度: O(n),n 是给定字符串的长度

辅助空间: O(n)