16: Implement a basic string compression algorithm.
⏳⌚ 00:00:00

Question:-

Implement a basic string compression algorithm.
Example 1:
Input: aaabbbcc
Output: a3b3c2
Example 2:
Input: abc
Output: abc

Steps to solve:-

1. compressString Function:-
compressString is a function that takes an input string str as a reference (to avoid making a copy of the string).
string compressed;: This creates an empty string compressed to store the compressed result.
int count = 1;: Initialize a counter variable count to keep track of consecutive characters.
Inside the for loop:
The loop iterates through each character of the input string using the variable i.
It checks if the current character is the same as the next character (checking for consecutive repetitions).
If consecutive characters are found, it increments the count.
If a different character is encountered or if we reach the end of the string, it appends the current character followed by the count to the compressed string, then resets the count to 1.
After the loop: It compares the length of the compressed string with the original string. If the compressed string is shorter, it returns the compressed string; otherwise, it returns the original string.
2. main function:-string input;: Declares a string variable input to store the user's input string.
cin >> input;: Reads a string from the standard input (keyboard) and stores it in the input variable.
Calls the compressString function with the input string, storing the result in the compressed variable.
Finally, it prints the compressed string to the standard output (console) using cout.

solution->

View Code 1
Time Complexity = O(n)
Space Complexity = O(n)