Write a program to do basic string compression. For a character which is consecutively repeated more than once, replace consecutive duplicate occurrences with the count of repetitions.
Example: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.
Note:
Consecutive count of every character in the input string is less than or equal to 9. You are not required to print anything. It has already been taken care of. Just implement the given function and return the compressed string.
The first and only line of input contains a string without any leading and trailing spaces.
Output Format:
The output contains the string after compression printed in single line
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.
It is mentioned that we only need to consider characters that are consecutively repeated more than once. We may use this information to solve this problem.
The steps are as follows:
O(N), Where ‘N' is the total number of characters or length of the string.
Since we iterate through all the characters once. Thus the time complexity will be O(N).
O(1)
Since we use constant space. Thus the space complexity will be O(1).