Advertisement
Slapoguzov

Untitled

Jan 22nd, 2024
579
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.89 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. public class Compression {
  4.     public static String compress(String input) {
  5.         if (input == null || input.isEmpty()) {
  6.             throw new IllegalArgumentException("Input cannot be null or empty.");
  7.         }
  8.         StringBuilder compressed = new StringBuilder();
  9.         char currentChar = input.charAt(0);
  10.         int count = 1;
  11.  
  12.         for (int i = 1; i < input.length(); i++) {
  13.             char nextChar = input.charAt(i);
  14.             if (nextChar == currentChar) {
  15.                 count++;
  16.             } else {
  17.                 compressed.append(currentChar).append("±").append(count);
  18.                 currentChar = nextChar;
  19.                 count = 1;
  20.             }
  21.         }
  22.  
  23.         compressed.append(currentChar).append("±").append(count);
  24.  
  25.         return compressed.toString();
  26.     }
  27.  
  28.     public static String decompress(String input) {
  29.         if (input == null || input.isEmpty()) {
  30.             throw new IllegalArgumentException("Input cannot be null or empty.");
  31.         }
  32.  
  33.         StringBuilder decompressed = new StringBuilder();
  34.         String[] tokens = input.split("±");
  35.  
  36.         if (tokens.length % 2 != 0) {
  37.             throw new IllegalArgumentException("Invalid compressed input.");
  38.         }
  39.  
  40.         for (int i = 0; i < tokens.length; i += 2) {
  41.             char character = tokens[i].charAt(0);
  42.             int count = Integer.parseInt(tokens[i + 1]);
  43.  
  44.             if (count < 1) {
  45.                 throw new IllegalArgumentException("Invalid compressed count.");
  46.             }
  47.  
  48.             for (int j = 0; j < count; j++) {
  49.                 decompressed.append(character);
  50.             }
  51.         }
  52.  
  53.         return decompressed.toString();
  54.     }
  55.  
  56.     public static void main(String[] args) {
  57.         String decompressed = decompress("A±2147483647");
  58.         System.out.println("Decompressed: " + decompressed);
  59.     }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement