STRING COMPRESSION
Take as input S, a string. Write a function that does basic string compression. Print the value returned. E.g. for input “aaabbccds” print out a3b2c2d1s1.
Input Format:
A single String S
Constraints:
1 < = length of String < = 100
Output Format
The compressed String.
Sample Input
aaabbccds
Sample Output
a3b2c2d1s1
Answer
#include
#include
using namespace std;
void stringCompression(string s,int n){
int count = 1;
cout << s[0] ;
if(n==1){
cout << count ;
}
for (int i = 1; i < n; ++i){
if(s[i] == s[i-1]){
count ++;
}else{
cout << count ;
cout << s[i];
count = 1 ;
}
}
cout << count << endl ;
}
int main(){
string s;
cin >> s;
int n = s.length();
stringCompression(s,n);
}
1 test case is showing wrong answer