📜  按给定字符串的字符频率降序生成数字

📅  最后修改于: 2021-10-27 07:13:22             🧑  作者: Mango

给定一个长度为N的字符串Str ,由小写字母组成,任务是按照给定字符串中字符出现频率的降序生成一个数字。如果两个字符具有相同的频率,以更小的ASCII值的字符首先出现。分配给字符{a, b, …., y, z} 的数字分别为 {1, 2, …., 25, 26}。
注意:对于分配给它的值大于9 的字符,取其模 10。
例子:

方法:
请按照以下步骤解决问题:

  • 初始化 Map 并存储每个字符的频率。
  • 遍历Map并将所有 { 字符, Frequency } 对插入到成对的向量中。
  • 以这样的方式对该向量进行排序,使得频率较高对首先出现,并且在具有相同频率的对中,具有较小 ASCII 值的那些先出现。
  • 遍历这个向量并找到每个字符对应的数字。
  • 打印生成的最终数字。

下面是上述方法的实现:

C++
// C++ Program to implement
// the above approach
#include 
using namespace std;
 
// Custom comparator for sorting
bool comp(pair& p1,
          pair& p2)
{
 
    // If frequency is same
    if (p1.second == p2.second)
 
        // Character with lower ASCII
        // value appears first
        return p1.first < p2.first;
 
    // Otherwise character with higher
    // frequency appears first
    return p1.second > p2.second;
}
 
// Function to sort map accordingly
string sort(map& m)
{
 
    // Declaring vector of pairs
    vector > a;
 
    // Output string to store the result
    string out;
 
    // Traversing map and pushing
    // pairs to vector
    for (auto x : m) {
 
        a.push_back({ x.first, x.second });
    }
 
    // Using custom comparator
    sort(a.begin(), a.end(), comp);
 
    // Traversing the Vector
    for (auto x : a) {
 
        // Get the possible digit
        // from assigned value
        int k = x.first - 'a' + 1;
 
        // Ensures k does not exceed 9
        k = k % 10;
 
        // Apppend each digit
        out = out + to_string(k);
    }
 
    // Returning final result
    return out;
}
 
// Function to generate and return
// the required number
string formString(string s)
{
    // Stores the frequencies
    map mp;
 
    for (int i = 0; i < s.length(); i++)
        mp[s[i]]++;
 
    // Sort map in required order
    string res = sort(mp);
 
    // Return the final result
    return res;
}
 
// Driver Code
int main()
{
    int N = 4;
 
    string Str = "akkzzz";
 
    cout << formString(Str);
 
    return 0;
}


Python3
# Python3 Program to implement
# the above approach
 
# Function to sort map
# accordingly
def sort(m):
 
    # Declaring vector
    # of pairs
    a = {}
 
    # Output string to
    # store the result
    out = ""
 
    # Traversing map and
    # pushing pairs to vector
    for x in m:
        a[x] = []
 
        a[x].append(m[x])
 
    # Character with lower ASCII
    # value appears first
    a = dict(sorted(a.items(),
                  key = lambda x : x[0]))
 
    # Character with higher
    # frequency appears first
    a = dict(sorted(a.items(),
                    reverse = True,
                    key = lambda x : x[1]))
 
    # Traversing the Vector
    for x in a:
 
        # Get the possible digit
        # from assigned value
        k = ord(x[0]) - ord('a') + 1
 
        # Ensures k does
        # not exceed 9
        k = k % 10
 
        # Apppend each digit
        out = out + str(k)
 
    # Returning final result
    return out
 
# Function to generate and return
# the required number
def formString(s):
 
    # Stores the frequencies
    mp = {}
    for i in range(len(s)):
        if s[i] in mp:
            mp[s[i]] += 1
        else:
            mp[s[i]] = 1
 
    # Sort map in
    # required order
    res = sort(mp)
 
    # Return the
    # final result
    return res
 
# Driver Code
N = 4
Str = "akkzzz"
print(formString(Str))
 
# This code is contributed by avanitrachhadiya2155


输出:
611

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

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程