Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- public class Compression {
- public static String compress(String input) {
- if (input == null || input.isEmpty()) {
- throw new IllegalArgumentException("Input cannot be null or empty.");
- }
- StringBuilder compressed = new StringBuilder();
- char currentChar = input.charAt(0);
- int count = 1;
- for (int i = 1; i < input.length(); i++) {
- char nextChar = input.charAt(i);
- if (nextChar == currentChar) {
- count++;
- } else {
- compressed.append(currentChar).append("±").append(count);
- currentChar = nextChar;
- count = 1;
- }
- }
- compressed.append(currentChar).append("±").append(count);
- return compressed.toString();
- }
- public static String decompress(String input) {
- if (input == null || input.isEmpty()) {
- throw new IllegalArgumentException("Input cannot be null or empty.");
- }
- StringBuilder decompressed = new StringBuilder();
- String[] tokens = input.split("±");
- if (tokens.length % 2 != 0) {
- throw new IllegalArgumentException("Invalid compressed input.");
- }
- for (int i = 0; i < tokens.length; i += 2) {
- char character = tokens[i].charAt(0);
- int count = Integer.parseInt(tokens[i + 1]);
- if (count < 1) {
- throw new IllegalArgumentException("Invalid compressed count.");
- }
- for (int j = 0; j < count; j++) {
- decompressed.append(character);
- }
- }
- return decompressed.toString();
- }
- public static void main(String[] args) {
- String decompressed = decompress("A±2147483647");
- System.out.println("Decompressed: " + decompressed);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement