[英]Implement a function which takes a string as an input and returns a new one without consonant letters replaced with “!”
[英]function which takes a string as input and returns the most frequent character
我寫了一個功能。 它工作正常。 但在我看來,這不是最優的。 但是我還沒有找到可以用來釋放它的標准功能。 因為我把它變成了一種簡單的值。 而且執行需要很長時間
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;
}
這是我使用標准庫編寫它的方式:
#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;
}
但老實說,我對手動迭代字符串以計算其字符不滿意。 在實際代碼中,我可能會抽象出頻率表的創建,它可能還有一個max
function。 在 Python 中,這直接對應於collections.Counter
class。 如果我們假設存在此實用程序 class(留給讀者作為練習),則實現變為
char most_frequent_char(std::string_view str) {
return max(freq_table{str}).first;
}
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.