Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * @Author: FamiHug at FAMILUG
- * @Version: 1.0 Tue Aug 2 23:53:23 ICT 2011
- */
- public class PRC01CompressString {
- public static void main(String[] args)
- {
- StringZipper sz = new StringZipper();
- System.out.println("Programming Challenger 01 - FAMILUG\u2122 \n");
- String input = "AAABBCAABDDAFF";
- System.out.println("Input: " + input + "\n");
- String compressed = sz.compress(input);
- System.out.println("Compressed: " + compressed);
- String extracted = sz.extract(compressed);
- System.out.println("Extracted: " + extracted);
- }
- }
- class StringZipper {
- public String compress(String input)
- {
- int charCounter = 1;
- char currentChar = input.charAt(0);
- char previousChar;
- StringBuffer compressedString = new StringBuffer();
- for(int i = 1; i < input.length(); i++) {
- previousChar = currentChar;
- currentChar = input.charAt(i);
- if(currentChar == previousChar) {
- charCounter++;
- }
- else {
- if(charCounter != 1) {
- //System.out.print(charCounter + "" + previousChar);
- compressedString.append(charCounter);
- compressedString.append(previousChar);
- }
- else compressedString.append(previousChar);
- charCounter = 1;
- }
- }
- compressedString.append(charCounter);
- compressedString.append(currentChar);
- compressedString.append("\n");
- //System.out.println(charCounter + "" + currentChar);
- return compressedString.toString();
- }
- public String extract(String compressedString) {
- int loopTimes = 0;
- int currentChar;
- StringBuffer extracted = new StringBuffer();
- for(int i = 0; i < compressedString.length(); i++)
- {
- if(Character.isDigit(compressedString.charAt(i))) loopTimes = loopTimes * 10 + Character.digit(compressedString.charAt(i), 10);
- else
- {
- if(loopTimes == 0) loopTimes = 1;
- for(int j = 0; j < loopTimes; j++) {
- //System.out.print(compressedString.charAt(i));
- extracted.append(compressedString.charAt(i));
- }
- loopTimes = 0;
- }
- }
- //System.out.println();
- extracted.append("\n");
- return extracted.toString();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement