HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaModerate

Decompressing a string

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
stringdecompressingstackoverflow

Problem

We are given a string which is compressed and we have to decompress it.


(a(bc2)d2)$

"$" indicates end of string.


(abcbcd2)$


abcbcdabcbcd (This is the final uncompressed string.)

My code:

import java.util.*;

class decompress
{
    public static void main(String[] ar)
    {
        int end = 0, st = 0;
        Scanner sc = new Scanner(System.in);
        System.out.print(">> ");
        String s = sc.next();
        while(s.indexOf('(') != -1)
        {
        for(int i = 0; i < s.length(); i++)
        {
            char c = s.charAt(i);
            if(c == '(')
                st = i;
            else if(c == ')')
            {
                end = i;
                String t = s.substring(st+1,end);
                int n = t.charAt(t.length()-1) - '0';
                t = t.substring(0,t.length() - 1);
                String q = "";
                for(int j = 0; j < n; j++)
                    q += t;
                String m = "";
                if(st != 0)
                    m = s.substring(0,st);
                s = m + q + s.substring(i+1);
                break;
            }
        }
        }
        System.out.println(s);
     }
}


Is there a more elegant way to make this program ?

Solution

-
Indentation. If you are using Eclipse, please select all your code and press Ctrl + I. Your entire for-loop should be indented one step further.

-
Use methods. One method for inputting a String, one method for making one iteration of the "decompression".

-
Did you forget about how to properly use indexOf suddenly? You use indexOf as a condition for your while loop, that makes sense. But then you're using a for-loop to determine the location of the ( and ) characters you are going to work with. This makes no sense to me.

-
Better variable names. Thanks to your comments on your question, I managed to figure out parts of what you are doing and write a review about that. However, Daniel still has a point that your code is not readable.

-
Close the scanner. Your scanner is a resource that needs to be closed, call sc.close(); as soon as you are done with the scanner (that is, after you have received all the required inputs from it)

-
Potential problems. What if I want to encrypt the string (thisWillMessWithYourCode2), how should that string be encrypted in order to be decrypted correctly? Or what would happen if I gave your program the input 42)invalid(data? I believe your code would have a hard time with that.

Context

StackExchange Code Review Q#37763, answer score: 10

Revisions (0)

No revisions yet.