Compress String in C++


Suppose we have a string s, we have to eliminate consecutive duplicate characters from the given string and return it. So, if a list contains consecutive repeated characters, they should be replaced with a single copy of the character. The order of the elements will be same as before.

So, if the input is like "heeeeelllllllloooooo", then the output will be "helo"

To solve this, we will follow these steps −

  • ret := a blank string

  • for initialize i := 0, when i < size of s, update (increase i by 1), do −

    • if size of ret is non-zero and last element of ret is same as s[i], then −

      • Ignore following part, skip to the next iteration

    • ret := ret concatenate s[i]

  • return ret

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   string solve(string s) {
      string ret = "";
      for(int i = 0; i < s.size(); i++){
         if(ret.size() && ret.back() == s[i]){
            continue;
         }
         ret += s[i];
      }
      return ret;
   }
};
int main(){
   Solution ob;
   cout << (ob.solve("heeeeelllllllloooooo"));
}

Input

"heeeeelllllllloooooo"

Output

helo

Updated on: 02-Sep-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements