📜  打印字符串中频率为 K 次方的所有字符

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

打印字符串中频率为 K 次方的所有字符

给定大小为N的字符串str ,任务是以字典顺序打印频率为K的幂的字符串的字符。

例子:

天真的方法:这个想法是计算字符串中每个字母的频率,如果频率是K的幂,则将其添加到新字符串中。对字符串进行排序并打印。

时间复杂度: O(N 2 )
辅助空间: O(N)

有效的方法:这个想法是使用散列。以下是步骤:

  • 遍历字符串并将每个字母的频率存储在一个 Map 中
  • 遍历地图并打印频率为 K 次方的字母

下面是上述方法的实现:

C++
// C++ implementation for the above approach
 
#include 
using namespace std;
 
// Function to count the frequency
// of every alphabet in the string
// and print the alphabets with
// frequency as the power of K
void countFrequency(string str, int N, int K)
{
 
    // Map will store the frequency
    // of each alphabet of the string
    map freq;
 
    // Store the frequency of each
    // alphabet of the string
    for (int i = 0; i < N; i++) {
 
        freq[str[i]]++;
    }
 
    // Traverse the Map
    for (auto i : freq) {
 
        // Calculate log of the
        // current string alphabet
        int lg = log2(i.second);
 
        // Power of 2 of the log value
        int a = pow(2, lg);
 
        if (a == i.second) {
            while (a--)
                cout << i.first << endl;
        }
    }
}
 
// Driver Code
int main()
{
 
    string str = "aaacbb";
 
    // Size of string
    int N = str.size();
 
    // Initialize K
    int K = 2;
 
    // Function call
    countFrequency(str, N, K);
 
    return 0;
}


Java
// Java implementation for the above approach
import java.util.*;
 
class GFG{
 
// Function to count the frequency
// of every alphabet in the String
// and print the alphabets with
// frequency as the power of K
static void countFrequency(String str, int N, int K)
{
     
    // Map will store the frequency
    // of each alphabet of the String
    HashMap freq = new HashMap();
 
    // Store the frequency of each
    // alphabet of the String
    for(int i = 0; i < N; i++)
    {
         
        if (freq.containsKey(str.charAt(i)))
        {
            freq.put(str.charAt(i),
            freq.get(str.charAt(i)) + 1);
        }
        else
        {
            freq.put(str.charAt(i), 1);
        }
    }
 
    // Traverse the Map
    for(Map.Entry i : freq.entrySet())
    {
         
        // Calculate log of the
        // current String alphabet
        int lg = (int)Math.ceil(Math.log(i.getValue()));
 
        // Power of 2 of the log value
        int a = (int)Math.pow(2, lg);
 
        if (a == i.getValue())
        {
            while (a-->0)
                System.out.print(i.getKey() + "\n");
        }
    }
}
 
// Driver Code
public static void main(String[] args)
{
    String str = "aaacbb";
 
    // Size of String
    int N = str.length();
 
    // Initialize K
    int K = 2;
 
    // Function call
    countFrequency(str, N, K);
}
}
 
// This code is contributed by shikhasingrajput


Python3
# Python code for the above approach
import math
 
# Function to count the frequency
# of every alphabet in the string
# and print the alphabets with
# frequency as the power of K
def countFrequency(str, N, K):
 
    # Map will store the frequency
    # of each alphabet of the string
    freq = {}
 
    # Store the frequency of each
    # alphabet of the string
    for i in range(N):
        if str[i] in freq.keys():
            freq[str[i]] = freq[str[i]] + 1
        else:
            freq[str[i]] = 1
 
    # Traverse the Map
    for i in sorted(freq.keys()):
 
        # Calculate log of the
        # current string alphabet
        lg = math.floor(math.log2(freq[i]))
 
        # Power of 2 of the log value
        a = math.pow(2, lg)
 
        if a == freq[i]:
            while a != 0:
                print(i)
                a = a - 1
 
# Driver Code
str = "aaacbb"
 
# Size of string
N = len(str)
 
# Initialize K
K = 2
 
# Function call
countFrequency(str, N, K)
 
# This code is contributed by Potta Lokesh


C#
// C# code for the above approach
using System;
using System.Collections;
using System.Collections.Generic;
 
class GFG
{
// Function to count the frequency
// of every alphabet in the String
// and print the alphabets with
// frequency as the power of K
static void countFrequency(string str, int N, int K)
{
     
    // Map will store the frequency
    // of each alphabet of the String
    Dictionary freq =
          new Dictionary();
 
    // Store the frequency of each
    // alphabet of the String
    foreach(char i in str)
    {
        if(freq.ContainsKey(i))
        {
          freq[i]++;
        }
        else
        {
          freq[i]=1;
        }
    }
    ArrayList ch = new ArrayList();
    // Traverse the dict
    foreach(KeyValuePair i in freq)
    {
         
        // Calculate log of the
        // current String alphabet
        int lg = (int)Math.Ceiling(Math.Log(i.Value));
 
        // Power of 2 of the log value
        int a = (int)Math.Pow(2, lg);
        if (a == i.Value)
        {
            while (a-->0)
                ch.Add(i.Key);
        }
    }
    ch.Sort();
    for(int i = 0; i < ch.Count; i++){
        Console.Write(ch[i] + "\n");
    }
}
 
// Driver Code
public static void Main () {
     
    string str = "aaacbb";
 
    // Size of String
    int N = str.Length;
 
    // Initialize K
    int K = 2;
 
    // Function call
    countFrequency(str, N, K);
}
}
 
// This code is contributed by Samim Hossain Mondal.


Javascript


输出
b
b
c

时间复杂度: O(N * log N)
辅助空间: O(N)