
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Advertisements