Nhập vào từ bàn phím một xâu kí tự S. Hãy viết ra một kí tự có số lần xuất hiện nhiều nhất trong xâu S (có phân biệt kí tự hoa và kí tự thường). c++
Quảng cáo
2 câu trả lời 173
#include <iostream>
#include <map>
int main() {
std::string S;
std::cin >> S;
std::map<char, int> freq;
for (char c : S) {
freq[c]++;
}
char max_char = S[0];
int max_freq = freq[S[0]];
for (auto it : freq) {
if (it.second > max_freq) {
max_freq = it.second;
max_char = it.first;
}
}
std::cout << "Kí tự xuất hiện nhiều nhất: " << max_char << std::endl;
return 0;
}
def most_common_character(s):
char_count = {}
for char in s:
char_count[char] = char_count.get(char, 0) + 1
max_count = max(char_count.values())
most_common_chars = [char for char, count in char_count.items() if count == max_count]
return most_common_chars[0]
# Nhập xâu từ bàn phím
input_string = input("Nhập vào một xâu kí tự: ")
# Tìm kí tự xuất hiện nhiều nhất
most_common = most_common_character(input_string)
print("Kí tự xuất hiện nhiều nhất là:", most_common)
Quảng cáo