

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#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
- Related Questions & Answers
- How to compress and un-compress the data of a file in Java?
- Best Way to compress mysqldump?
- How to compress a file in Java?
- How to un-compress a file in Java?
- How we can compress large Python files?
- Compress The Schedule to Hit The Target
- Compress array to group consecutive elements JavaScript
- How to Compress files with ZIPFILE module in Python.
- How to compress Python objects before saving to cache?
- How to optimize and compress jpeg or png images in linux
- The best way to compress and extract files using the tar command on linux
- Equals(String, String) Method in C#
- String Literal Vs String Object in C#
- String Transforms Into Another String in Python
- Hyphen string to camelCase string in JavaScript
Advertisements