Skip to main content

Run Length Encoding

Task: Given a string, Find the run length encoded string for given string.

Example:
1
aaaabbbccc
Output:
a4b3c3

Here is the Code:
Program in C++:

  1. #include<iostream>
  2. #include<bits/stdc++.h>
  3. using namespace std;
  4. char *encode(char *src)
  5. {     
  6.   int c=0;
  7.   for(int i=0;src[i]!='\0';i++)
  8.   {
  9.       if(c==0)
  10.       {
  11.           cout<<src[i];
  12.           c++;
  13.       }
  14.       else if(src[i-1]==src[i])
  15.       {
  16.           c++;
  17.       }
  18.       else 
  19.       {
  20.           cout<<c;
  21.           c=1;
  22.           cout<<src[i];
  23.       }
  24.   }
  25.   cout<<c;
  26.   return "\0";
  27. }
  28. int main() {
  29.     int T;
  30.     cin>>T;
  31.     while(T--)
  32.     {
  33.         char str[10000];
  34.         cin>>str;
  35.         cout<<encode(str)<<endl;
  36.     }
  37.     return 0;
  38. }    

Here is the Video: