Compress the String

Ninja has been given a program to do basic string compression. For a character that is consecutively repeated more than once, he needs to replace the 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 :

The consecutive count of every character in the input string is less than or equal to 9.
Input Format:
The first line contains an integer 'T' which denotes the number of test cases or queries to be run.

The first line of each test case contains one string ‘S’ denoting the input string that needs to be compressed.
Output Format:
For each case, we need to print a string representing the compressed string.

The output of each test case will be printed in a separate line.
Note:
You do not need to input or print anything, and it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 5
1 <= |S| <= 5000

Where |S| is the size of the string.

Time Limit: 1 sec
CodingNinjas
author
2y

This was nothing but the Run Length Encoding Algorithm which I was familiar with. So I coded it preety fast.

Algorithm :

1) Pick the first character from the source string.
2) Append the picked character...read more

CodingNinjas
author
2y
Greedy Approach

Here, we can simply traverse the string and run two loops where the outer loop will hold the unique characters and the inner loop will count the consecutive repetitions of that characte...read more

Anonymous
6mo
import java.util.LinkedHashMap; public class Main { public static void main(String[] args) { String s="iyyer"; String s1=""; char [] ch=s.toCharArray(); for(char i:ch){ System.out.print(i+" "); } Link...read more
Add answer anonymously...
CGI Group Software Engineer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter