Run length encoding of the string in C++

In this tutorial, we will learn to find run length encoding of a string in c++.

For Example: 

  • Given string: “ssshhhhhaiiiiillllll”
  • Now, encode the length of every character.
  • Output: s3h5a1i5l6
  • If the given string is “mmmmaaniiii”
  • Then, the function will return to m4a2n1i4.

Try to solve this in less time complexity. So, we have a simple approach.

Run length encoding is a presenting form of lossless data compression which works on sequences having the same character occurring consecutively and it will encode the sequence and will store only the single value.

RLE Approach:

The following steps are:

  • Firstly, pick the first character of the given string.
  • Then, take a second string and append the character to this string.
  • Now, count the number of occurrences of that character in the given string.
  • And let this count be x. Append this x to the second string.
  • Now, we will move to the next character of the given string and we will do the same.
  • Finally, we will follow the same steps until we reach to the last character of the string.
  • The time complexity is O(n).you may also like:
    How to Validate a phone number in C++?

Program of Run length encoding of a string in C++

Hence, you can see the implementation of the above approach below.

//  run-length encoding 
#include <bits/stdc++.h>
#include<iostream>
using namespace std; 

void printfunction(string fs) 
{ 
  int mni = fs.length(); 
  for (int i = 0; i < mni; i++) { 

    // Count occurrences  
    int cnt = 1; 
    while (i < mni - 1 && fs[i] == fs[i + 1]) { 
      cnt++; 
      i++; 
    } 

    // Print the character and the count 
    cout << fs[i] << cnt; 
  } 
} 

int main() 
{ 
  string fs = "ssshhhhhaiiiiillllll"; 
  printfunction(fs); 
  return 0; 
} 

OUTPUT EXPLANATION:




 

INPUT: "ssshhhhhaiiiiillllll" 

OUTPUT: s3h5a1i5l6


Leave a Reply

Your email address will not be published. Required fields are marked *