Goldman Sachs | Coderpad | Run Length Encoding
Anonymous User
893

Convert a string as given in the format below:

Example:
aabbb into a2b3
aaaa into a4
a into a1

import java.util.Scanner;

public class StringComp {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("Enter the string: ");
		String s = sc.next();
		sc.close();
		System.out.println("The compressed string: " + compressedString(s));
	}

	private static String compressedString(String s) {

		StringBuilder sb = new StringBuilder();
		int count = 1;
		for (int i = 0; i < s.length(); i++) {
			if (i + 1 < s.length() && s.charAt(i) == s.charAt(i + 1)) {
				count++;
			} else {
				sb.append(s.charAt(i));
				if (count > 1) {
					sb.append(count);
				}
				count = 1;
			}
		}
		return sb.length() < s.length() ? sb.toString() : s;
	}
}
Comments (3)