Run Length Encoding
PROBLEM :
Given a string, Your task is to complete the function encode that returns the run length encoded string for the given string.
eg if the input string is “wwwwaaadexxxxxx”, then the function should return “w4a3d1e1x6?.
You are required to complete the function encode that takes only one argument the string which is to be encoded and returns the encoded string.
Input (To be used only for expected output):
The first line contains T denoting no of test cases . Then T test cases follow . Each test case contains a string str which is to be encoded .
Output:
For each test case output in a single line the so encoded string .
Constraints:
1<=T<=100
1<=length of str<=100
Example:
Input
2
aaaabbbccc
abbbcdddd
Output
a4b3c3
a1b3c1d4
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
/*You are required to complete this function */
char *encode(char *src)
{
char *str ;
int i,k,l,c;
str=(char*)malloc(100*sizeof(char)) ;
l=strlen(src) ;
c=1 ;
for(i=0;i<l;i++)
{
while(src[i]==src[i+1])
{
i++ ;
c++ ;
}
str[k++]=src[i] ;
str[k++]=c+48 ;
c=1 ;
}
str[k]='\0' ;
return str ;
}
---------------------------------------------------------------------------------
Given a string, Your task is to complete the function encode that returns the run length encoded string for the given string.
eg if the input string is “wwwwaaadexxxxxx”, then the function should return “w4a3d1e1x6?.
You are required to complete the function encode that takes only one argument the string which is to be encoded and returns the encoded string.
Input (To be used only for expected output):
The first line contains T denoting no of test cases . Then T test cases follow . Each test case contains a string str which is to be encoded .
Output:
For each test case output in a single line the so encoded string .
Constraints:
1<=T<=100
1<=length of str<=100
Example:
Input
2
aaaabbbccc
abbbcdddd
Output
a4b3c3
a1b3c1d4
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
/*You are required to complete this function */
char *encode(char *src)
{
char *str ;
int i,k,l,c;
str=(char*)malloc(100*sizeof(char)) ;
l=strlen(src) ;
c=1 ;
for(i=0;i<l;i++)
{
while(src[i]==src[i+1])
{
i++ ;
c++ ;
}
str[k++]=src[i] ;
str[k++]=c+48 ;
c=1 ;
}
str[k]='\0' ;
return str ;
}
---------------------------------------------------------------------------------
Comments
Post a Comment