Strings-String Compression [codingblocks]

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 a3b2c2ds.

Input Format
A single String S.

Constraints
A string of length between 1 to 1000

Output Format
The compressed String.

Sample Input
aaabbccds

Sample Output
a3b2c2ds

Explanation
In the given sample test case 'a' is repeated 3 times consecutively, 'b' is repeated twice, 'c' is repeated twice. But, 'd' and 's' occurred only once that's why we do not write their occurrence.


Java Code:

/*
Amit Kumar
14-12-2020
IDE Code: https://ide.geeksforgeeks.org/btZOsVDRAd
*/

package String;
import java.util.Scanner;

public class Strings_StringCompression {
    public static Scanner scanner = new Scanner(System.in);
    public static void main(String[] args) {
        String str = scanner.next();
        StringBuilder stringBuilder = new StringBuilder();
        int count = 1;
        for (int i=1; i<str.length(); i++) {
            if (str.charAt(i-1) == str.charAt(i)) {
                count ++;
            } else {
                stringBuilder.append(str.charAt(i-1));
                if (count != 1)
                    stringBuilder.append(count);
                count = 1;
            }
        }
        stringBuilder.append(str.charAt(str.length()-1));
        if (count != 1)
            stringBuilder.append(count);
        System.out.println(stringBuilder.toString());
    }
}

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )