This is my code please help me to corret this
Max frequency character problem
@akshat42bajpai good try your logic seems perfect there are some simple mistakes that you need to rectify
- after #include<bits/stdc++.h> type using namespace std;
- str.len(str) - > function syntax is not correct instead it should be str.length().
- for(int i=0;i<len;i++){
freq[str[i]]++;
if(max<freq[str[i]]){
max = freq[str[i]];
result= str[i];
}
}
should be changed to
for(int i=0;i<len;i++){
freq[str[i]-‘a’]++;
if(max<freq[str[i]-‘a’]){
max = freq[str[i]-‘a’];
result= str[i];
}
}
freq[str[i]] will go out of bounds as str[i] is a character lets suppose str[i]=‘A’ then index will become the ASCII value of ‘A’ which is 65 so freq[65] will go out of bounds as max size of freq array is 26 so we subtract ‘A’ to get the index under 26.
eg- str[i] = ‘B’ ascii value of B = 66
ascii value of A is 65 so freq[str[i]-‘A’] = freq[66-65]=freq[1]
you can refer the below code to rectify your code to produce correct result
#include <bits/stdc++.h>
using namespace std;
// #include
// #include
void MaxCharacter(string &str){
// make a frequency array for all the alphabets
// with index zero
int freq[26] = {0};
// construct character count array from input string
int len = str.length();
int max = 0;
char result; //intitiliaze the result
// traverse through the string for mapping
for(int i=0;i<len;i++){
freq[str[i]-'a']++;
if(max<freq[str[i]-'a']){
max = freq[str[i]-'a'];
result= str[i];
}
}
cout<<result;
}
int main() {
string str;
getline(cin, str);
MaxCharacter(str);
return 0;
}
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.