简体   繁体   中英

function which takes a string as input and returns the most frequent character

I wrote a feature. And it works correctly. But in my opinion it is not optimal. But I have not found what standard features you can use to unleash it. Since I made it a simple sort of values. And it takes a long time to execute

char getMaxOccuringChar(char* str) 
{ 
    int count[ASCII_SIZE] = {0}; 

    int len = strlen(str); 
    int max = 0; 
    char result; 

    for (int i = 0; i < len; i++) { 
        count[str[i]]++; 
        if (max < count[str[i]]) { 
            max = count[str[i]]; 
            result = str[i]; 
        } 
    } 

    return result; 
} 

Here's how I'd write this using the standard library:

#include <algorithm>
#include <unordered_map>
#include <string_view>

char most_frequent_char(std::string_view str) {
    std::unordered_map<char, int> counts;
    for (auto c : str) counts[c] += 1;
    return std::max_element(
        begin(counts), end(counts),
        [](auto a, auto b) {return a.second < b.second;}
    )->first;
}

But to be honest I'm not happy with manually iterating over the string to counts its characters. In actual code I'd probably abstract away the creation of a frequency table , which would presumably also have a max function. In Python this directly corresponds to the collections.Counter class. If we assume the existence of this utility class (left as an exercise to the reader), the implementation becomes

char most_frequent_char(std::string_view str) {
    return max(freq_table{str}).first;
}

Use a map and max_element

char getMaxOccuringChar(char* str) 
{ 
    auto s = std::string(str);
    auto cmap = std::map<char, size_t>{}
    for (auto c : s) {
      cmap[c]++;
    }

    auto found = std::max_element(cmap.begin(), cmap.end(),
        [] (auto p1, auto p2) {
            return p1.second < p2.second;
        }
    );

    return found.first;
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM