Question: You are given a string like "aaaabbbcc", do an in place conversion which write frequency of each charater(which come continuosly) with that character. If character repeats only once don't write '1'.
Example:
input: aaabbbcc
output: a3b2c2
input: aabaa
output: a2ba2
Answer:
Answer is very simple but I am puting it here because generally candidates assume that a character can't come more than 9 tims and use freq+'0' to write its frequency. They fail if input is like "aaaaaaaaaa" then their outpur comes as "a:" 9 in place of "a10".
Code:
#include<stdio.h>
#include<malloc.h>
#include<string.h>
char* strr;
char* itoax(int n)
{
char *temp;
int i;
strr = (char*)malloc(10*sizeof(char));
temp = strr;
for(i=n; i>0; i=i/10)
*strr++ = '0'+ i%10;
*strr = '\0';
temp = strrev(temp);
return temp;
}
void main()
{
char in[100], out[100] = {0};
char *countarr;
int i, j, len, count;
i=j=count=0;
printf("Enter string: ");
scanf("%s", in);
len = strlen(in);
out[i] = in[j];
count = 1;
for(i=1,j=1;i<len;i++,j++)
{
while(in[i] == in[i-1])
{
count ++;
i++;
}
if (count > 1)
{
countarr = itoax(count);
strcat(out,countarr);
j+=strlen(countarr);
count=1;
}
out[j] = in [i];
}
out[j] = '\0';
printf("\n%s\n",out);
}
Subscribe - To get an automatic feed of all future posts subscribe here, or to receive them via email go here and enter your email address in the box. You can also like us on facebook and follow me on Twitter @akashag1001.
are you sure this is inplace?? I was asked this question and the constraint very well said, that we can't create a new string!!
Appreciate your blog otherwise..cheers..keep up the good work :)
@thereader: This is not actually in-place for the code simplicity. But you can very easily used in[] wherever I have used out[]. Just make sure that u r not using a strcat on in[] in line " strcat(out,countarr);" but do a char-by-char copy. Very easy to implement.
Yeah. Actually in my case I was also asked not to use any operations like strcat.So it actually came down to a good question wherein we had to maintain 2 pointers for read and write and also allocate extra space for end cases