📌  相关文章
📜  根据频率对字符串数组进行排序

📅  最后修改于: 2021-09-06 11:30:57             🧑  作者: Mango

给定一个字符串数组arr[] ,任务是根据每个字符串的频率,按升序对字符串数组进行排序。如果两个元素具有相同的频率,则将它们按字典顺序排序。

例子:

方法想法是使用自定义比较器按照以下步骤按频率对字符串数组进行排序。

  • 地图数据结构用于根据字符串的频率将字符串存储为 (frequency, 字符串) 对。
  • 在自定义比较器的帮助下对这些对进行排序,以便如果两个字符串具有不同的频率,则之前存储频率较低的字符串。否则,如果频率相同,则按字典顺序比较字符串。

下面是上述方法的实现:

C++
// C++ implementation to sort the
// array of strings by its frequency
 
#include 
using namespace std;
 
// Custom comparator function to
// sort the string by its frequency
bool cmp(pair x,
         pair y)
{
 
    // Condition to check if the
    // frequency of the string is less
    if (x.first < y.first) {
        return true;
    }
 
    // Condition to check if the
    // frequency of the string is greater
    else if (x.first > y.first) {
        return false;
    }
 
    // Condition when frequency of
    // the strings is equal
    else {
 
        // Condition to check if the
        // first string is lexicographically
        // smaller than second string
        if (x.second < y.second) {
            return true;
        }
        else {
            return false;
        }
    }
}
 
// Function to sort the array of strings
// by its frequency in the array
void printArraystring(string str[], int n)
{
    unordered_map m;
 
    // Loop to store the frequency
    // of a string in a hash-map
    for (int i = 0; i < n; i++) {
        m[str[i]]++;
    }
 
    // Iterator for the map
    vector > vec;
 
    // Loop to store the frequency and
    // string in a vector
    for (auto it = m.begin(); it != m.end();
         it++) {
        vec.push_back(
            make_pair(it->second, it->first));
    }
 
    // Sort the string
    // using custom comparator
    sort(vec.begin(), vec.end(), cmp);
 
    // Loop to print the sorted vector
    for (int i = 0; i < vec.size(); i++) {
        cout << vec[i].second << ", ";
    }
}
 
// Driver Code
int main()
{
    string arr[] = { "Geeks", "for", "Geeks",
                     "for", "arc" };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    // Function to perform sorting
    printArraystring(arr, n);
 
    return 0;
}


Python 3
# Python 3 implementation to sort the
# array of strings by its frequency
 
# Custom comparator function to
# sort the string by its frequency
def srt(x):
    for i in range(len(x)-1):
        for j in range(i+1,len(x)):
            if(x[i][0]>x[j][0]):
                temp = x[j]
                x[j] = x[i]
                x[i] = temp
            elif(x[i][0] == x[j][0]):
                if(x[i][1]


Javascript


输出:
arc, for, Geeks,

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live