Hi everyone.
I've been following this forum for sometime now but officially registered today. I'm a Java guy learning C++ now.
As an exercise I'm started to rewrite some of the Java code I had written (while I was learning it ) now in C++.
There are several questions here that helped me a lot. But I'm stuck now and need some help.
The problem I'm trying to solve is to count the max repeating char in an array. The idea is to keep an array of size 26 as a frequency array, arr[0] is for 'a', arr[1] is for 'b' and so on. Increment suitable location for every char in the input array and finally find the index with max count.
This is my Java function :
static char findMax(String str) {
int arr[] = new int[26];
int i;
for(i=0;i<str.length();i++)
arr[str.charAt(i) - 'a']++;
int maxFreq = arr[0];
int maxEleIndex = 0;
for(i=1;i<26;i++)
if(arr[i] > maxFreq) {
maxFreq = arr[i];
maxEleIndex = i;
}
return (char)(maxEleIndex + 'a');
}
And this is my C++ function:
char findMax(string str) {
int *arr = new int[26];
int i;
for(i=0;i<str.length();i++)
arr[str.at(i) - 'a']++;
int maxFreq = arr[0];
int maxEleIndex = 0;
for(i=1;i<26;i++)
if(arr[i] > maxFreq) {
maxFreq = arr[i];
maxEleIndex = i;
}
return (char)(maxEleIndex + 'a');
}
The code compiles fine, but does not give correct output, it reports incorrect char as max repeating. I've used pointer in place of reference, at function in place of charAt. What am I doing wrong?