Compress the String
Compress the String
Send Feedback
Compress the String
If a string has 'x' repeated 5 times, replace this "xxxxx" with "x5".
The string is compressed only when the repeated character count is more than 1.
Consecutive count of every character in the input string is less than or equal to 9.
The first and only line of input contains a string without any leading and trailing spaces.
The output contains the string after compression printed in single line.
You are not required to print anything. It has already been taken care of. Just implement the given function.
0 <= N <= 10^6
Where 'N' is the length of the input string.
Time Limit: 1 sec
aaabbccdsa
a3b2c2dsa
In the given string 'a' is repeated 3 times, 'b' is repeated 2 times, 'c' is repeated 2 times and 'd', 's' and 'a' and occuring 1 time hence no compression for last 3 characters.
aaabbcddeeeee
a3b2cd2e5
In the given string 'a' is repeated 3 times, 'b' is repeated 2 times, 'c' is occuring single time, 'd' is repeating 2 times and 'e' is repeating 5times.
#include <string>string getCompressedString(string &input) { // Write your code here. /*int n=0; for(int i=0;input[i]!='\0';i++){ n++; } int count=0; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ count++;
} cout<<input[i]<<count; }}*/ if (input.length() == 0) { return " "; } int s = 0; int e = 0; string str = ""; while (s < input.length()) { while ((e < input.length()) && (input[e] == input[s])) { e += 1; } int t = e - s; if (t != 1) { str += input[s]; str += (char)(t + '0'); } else { str += input[s]; } s = e; } return str;}
#include <iostream>#include <cstring>#include<string>using namespace std;
#include <string>string getCompressedString(string &input) { // Write your code here. /*int n=0; for(int i=0;input[i]!='\0';i++){ n++; } int count=0; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ count++;
} cout<<input[i]<<count; }}*/ if (input.length() == 0) { return " "; } int s = 0; int e = 0; string str = ""; while (s < input.length()) { while ((e < input.length()) && (input[e] == input[s])) { e += 1; } int t = e - s; if (t != 1) { str += input[s]; str += (char)(t + '0'); } else { str += input[s]; } s = e; } return str;}
int main() { int size = 1e6; string str; cin >> str; str = getCompressedString(str); cout << str << endl;}
Comments
Post a Comment