Given a string of letters from alphabet insert frequency of each character in the string.in O(n) time and O(1) space [on hold]
- by learner
Below is my attempt
void str_freq(char *str, int len)
{
char c;
int cnt=0;
c=str[0];
int i,j=0;
for(i=0;i<len;i++)
{
if(c==str[i])
{
cnt++;
}
else
{
c = str[i];
// printf(" %d ",cnt);
str[j] = str[i-1];
str[j+1] = (char)(((int)'0')+cnt);
j++;
cnt=0;
}
}
str[j+1]='\0';
printf("%s",str);
}
int main()
{
char str[] = "aaabbccccdeffgggg";
int length=strlen(str);
str_freq(str,length);
}
I am getting wrong answer abcdef1 instead of a3b2c4d1e1f2g4. Please let me know where I am going wrong.