Friday, 10 January 2014

Java: String Compression - How to compress string in the given format

Write a routine that takes as input a string such as "aabbccdef" and outputs "a2b2c2def" or "a4bd2g4" for "aaaabddgggg". Write a ship quality code.


import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

/**
 *
 * @author Sunshine
 */
public class Ques2 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String input = br.readLine().toLowerCase();
       StringBuilder result = new StringBuilder();
        char currentCharacter;
        int count;

        for(int i = 0; i < input.length(); i++) {
            currentCharacter = input.charAt(i);
            count = 1;
            while(i < input.length() - 1 && input.charAt(i + 1) == currentCharacter) {
                count++;
                i++;
            }
            result.append(currentCharacter);
            result.append(count);
        }

        System.out.println(""+result);
    }
}

No comments:

Post a Comment