#include<iostream>
using namespace std;
/**
* @brief findchar 给定一个长度不限的字符串,请找出该字符串中出现次数最多的那个字符,并打印出该字符及出现次数;
如果多个字符的出现次数相同,只打印首个字符;输出字符的大小写格式要与输入保持一致,大小写不敏感模式下,输出字符的大小写格式与该字符首次出现时
的大小写格式一致。实现时无需考虑非法输入。
* @param [in] st 输入的字符串
* @param [out] ch 出现次数最多的字符
* @param [out] cnt 出现次数最多的字符数
* @param [in] sensitive 是否大小写敏感
* @return 是否获取成功
*/
bool findchar(const string& st, char* ch, int* cnt, bool issensitive=true){
bool ret = true;
int table[52] = {0};
int max = 0, maxindex =0, index = -1;
if(st.length() <= 0)
return false;
string str = st;
for(unsigned int i=0; i<str.length(); i++) {
if((str.at(i) <= 'Z') && (str.at(i) >= 'A') ) {
index = static_cast<int>( str.at(i) - 'A');
table[index]++;
}
else if((str.at(i) <= 'z') && (str.at(i) >= 'a')){
index = static_cast<int>(str.at(i) - 'a') ;
index += 26;
table[index]++;
}
}
if(issensitive) {
for(int i=0; i<52;i++) {
if(max < table[i]){
max = table[i];
maxindex = i;
}
}
}
else{
for(int i=0; i<26;i++) {
table[i] = table[i] + table[i+26];
table[i+26] = 0;
}
for(int j=0; j<26; j++) {
if(max < table[j]) {
max = table[j];
}
}
for(unsigned int i=0; i<str.length();i++) {
int cnt = -1;
(str.at(i) > 'Z') ? (cnt = static_cast<int>(str.at(i) - 'a')) : \
( cnt = static_cast<int>(str.at(i) - 'A') );
if(table[cnt] == max){
(str.at(i) > 'Z') ? (maxindex = 26 + cnt ) : (maxindex = cnt);
break;
}
}
}
if((maxindex < 26) && (max>1) ) {
*ch = maxindex + 'A';
*cnt = max;
}
else if((maxindex >= 26) && (max>1) ) {
*ch = maxindex + 'a' - 26;
*cnt = max;
}
else if(max==1){
*ch = str.at(0);
*cnt = max;
}
return ret;
}
int main()
{
char ch = 0;
int cnt = 0;
string str = "SssssMaammmmmmmaAde";
if(findchar(str, &ch, &cnt, false))
cout << "ch: " << ch << " cnt: " << cnt << endl;
else
cout << "failed" << endl;
}